readline源码阅读及实现简易版readline

一、readline阅读思维导图

二、简版readline实现

function readline(callback) {
  function onKeyPress(s) {
    output.write(s);
    line += s;
    switch (s) {
      case '\r':
        input.pause(); // 会清空输入时output输出的内容
        callback(line.slice(1));
        break;
    }
  }

  const input = process.stdin;
  const output = process.stdout;
  let line = ''; // 记录输入的内容
  input.on('keypress', onKeyPress)
  emitKeypressEvents(input);
  input.setRawMode(true);
  input.resume();
}

function emitKeypressEvents(stream) {
  function onData(chunk) {
    g.next(chunk.toString());
  }

  const g = emitKeys(stream);
  g.next()
  stream.on('data', onData);
  // 输出一个大于符号
  g.next('>');

}

function* emitKeys(stream) {
  while (true) {
    const ch = yield;
    stream.emit('keypress', ch);
  }
}

readline((res) => {
  console.log('>' + res);
});
Copyright © imooc-lego (2020 - present) all right reserved,powered by GitbookFile Modify: 2021-06-27 08:04:56

results matching ""

    No results matching ""