我对 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);
}
});
发生错误的原因是键可能“未定义”并且不包含属性名称。
关于node.js - Node.js 的按键因数字而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32466329/