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) 

为什么会发生这个错误?

我如何只允许某些字符或至less不会崩溃?

阅读字符的正确方法是

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

从Nodejs.org

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

固定。

我没有检查key对象是否存在…例如:

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