目录

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

哦哈哈
26 声望9 粉丝

没比别人多什么天赋;只有努力💪、用心、重复