乐趣区

关于脚手架:inquirer命令行交互原理二手写readline实现

目录

inquirer 命令行交互原理?(一)readline 的实现办法和原理
inquirer 命令行交互原理?(二)手写 readline 实现

背景

上篇曾经具体的形容了 readline 源码的实现,当初就是来测验下学习的状况,手动来实现一个 readline

代码

(1) 先监听输出流

function stepRead(callback) {function onkeypress(s) {output.write(s);
  }
  const input = process.stdin;
  const output =  process.stdout;
  let line = '';

  emikeypressEvents(input);
  input.on('keypress', onkeypress);
};

function emikeypressEvents(stream) {function onData(chunk){g.next(chunk.toString())
  }
  const g = emitkeys(stream);
    g.next()
    stream.on('data',onData)
};

function *emitkeys(stream) {while(true){
    let ch = yield;
    stream.emit('keyPress',ch);
  }
}
stepRead();

(2) 一一字母监听输出流, 并返回后果

知识点:
input.setRawMode(true);
input.resume(); // 从新开始,重启

function stepRead(callback) {function onkeypress(s) {output.write(s);
    line += s;
    switch (s) {
      case '\r':
        input.pause();
        callback(line)
        break;
    }
  }
  const input = process.stdin;
  const output =  process.stdout;
  let line = '';

  emitKeypressEvents(input);
  input.on('keypress', onkeypress);

  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)
};

function* emitkeys(stream) {while(true){
    let ch = yield;
    stream.emit('keypress',ch);
  }
}
stepRead(function(s){console.log(s);
  console.log('answer=', s);
});

解说

(1)先将输出流和输入流进行缓存,将输出流要填写的信息放在 line 变量中;

const input = process.stdin;
 const output =  process.stdout;
 let line = '';

(2)调用 emitKeypressEvents(input),执行 emitkyes 的 Generator 函数。.next();stream.on('data',onData) 绑定输出流

function emitKeypressEvents(stream) {function onData(chunk){g.next(chunk.toString())
  }
  const g = emitkeys(stream);
    g.next()
    stream.on('data',onData) 
};
function* emitkeys(stream) {while(true){
    let ch = yield;
    stream.emit('keypress',ch);
  }
}

(3)input.on('keypress', onkeypress); 绑定了 onkeypress 事件;输入流写入信息;如果是回车(’\r’)的话,shitch 来进行判断。

  function onkeypress(s) {output.write(s); // 输出的信息进行打印
    line += s;
    switch (s) {
      case '\r':
        input.pause();
        callback(line)
        break;
    }
  }
退出移动版