node.js - Node.js 的按键因数字而崩溃

标签 node.js

我对 Node.js 还很陌生,在处理一些示例时遇到了按键问题

这是我的代码:

'use strict';

var keypress = require('keypress');

// Make `process.stdin` begin emitting "keypress" events
keypress(process.stdin);

// Listening for the "keypress" event
process.stdin.on('keypress', function (ch, key) {
    if (key.name == 'e') {
        console.log('Emergency landing!');
    };  

    if (key.name == 'l') {
        console.log('Landing...');
    }

    if (key.name == 'x') {
        console.log('Goodbye!');
        process.exit();
    }
});

process.stdin.setRawMode(true);
process.stdin.resume();

如果我按字母,这会起作用,但如果按数字和其他字符,则会崩溃。

/Users/napolux/rollingspider/rs-1.js:16
    if (key.name == 'e') {
           ^

TypeError: Cannot read property 'name' of undefined
    at ReadStream.<anonymous> (/Users/napolux/rollingspider/rs-1.js:16:9)
    at emitTwo (events.js:87:13)
    at ReadStream.emit (events.js:172:7)
    at emitKey (/Users/napolux/rollingspider/node_modules/keypress/index.js:406:12)
    at ReadStream.onData (/Users/napolux/rollingspider/node_modules/keypress/index.js:48:14)
    at emitOne (events.js:77:13)
    at ReadStream.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at ReadStream.Readable.push (_stream_readable.js:110:10)
    at TTY.onread (net.js:523:20)

为什么会出现这个错误?

如何只允许某些字符或至少不崩溃?

最佳答案

读取字符的正确方法是

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
    if (chunk !== null) {
      process.stdout.write('data: ' + chunk);
    }
});

来自Nodejs.org

发生错误的原因是键可能“未定义”并且不包含属性名称。

关于node.js - Node.js 的按键因数字而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32466329/

相关文章:

node.js - 错误: Body attribute missing in multipart while using googleapis node module

node.js - 动态匹配变量 Mongodb

javascript - 我无法安装特定的 Node 模块 [ejs]

javascript - 解析: JavaScript Promises issue

node.js - 更改模型后如何创建 Sequelize cli db 迁移

node.js - Vagrant ssh 提示 'no kex alg' 无法连接虚拟机

jetty - 对于类似 etherpad 的应用程序,node.js 与 jetty 相比如何?

node.js - 将 Jquery UI 与express.js 结合使用

Javascript |执行 for 循环的其他方法可能会在成功后中断?

javascript - "npm start"在 ghost (node.js) 中给出错误