关于脚手架: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;
    }
  }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理