首页 > 解决方案 > 在哪里可以找到 Node.js 中“按键”事件的文档

问题描述

在 Node.js 中,我们可以将'readline'模块配置为发出'keypress'如下事件:

const readline = require('readline');

readline.emitKeypressEvents(process.stdin);

if (process.stdin.isTTY) {
  process.stdin.setRawMode(true);
}

然后,我们可以像这样监听按键事件(例如监听Ctrl+ c):

process.stdin.on('keypress', (str, key) => {
  if (key.ctrl && key.name === 'c') {
    // do stuff
  }
});

这很好用,但我在https://nodejs.org/en/docs/'keypress'上找不到有关该事件的任何文档。

所以我的问题是:关于调用我的'keypress'-callback 时使用的参数的文档在哪里?

标签: node.js

解决方案


此处指定此详细信息是因为:

process.stdin是一个双工流,调用emitKeypressEvents(<IN/OUT>)将导致该readline模块将从中读取,process.stdin然后它将解析数据,然后将事件写入output流调用write,因此您要查找的文档是在该函数上编写的。

emitKeypressEvents将相同的输入参数设置为输入和输出,而不是createInterface您可以定义一个用于输入和一个用于输出(您必须在其中附加on(keypress)事件。

一个要理解的小操场:

const readline = require('readline');
const { Readable } = require('stream');

const inStream = new Readable({
  read() { console.log('in reading'); }
});

let i = 0
setInterval(() => { inStream.push(`${i++}`) }, 1000)
readline.emitKeypressEvents(inStream);

inStream.on('keypress', (...ar) => {
  console.log(ar)
});

推荐阅读