node.js在数字上崩溃的按键
我是node.js的新手,在使用一些示例时,我遇到了按键问题 这是我的代码: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
'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)
/Users/napolux/rollingspider/rs-1.js:16
如果(key.name='e'){
^
TypeError:无法读取未定义的属性“name”
在ReadStream上。(/Users/napolux/rollingspider/rs-1.js:16:9)
两点钟(events.js:87:13)
在ReadStream.emit(events.js:172:7)
在emitKey(/Users/napolux/rollingspider/node_modules/keypress/index.js:406:12)
在ReadStream.onData(/Users/napolux/rollingspider/node_modules/keypress/index.js:48:14)
在emitOne(events.js:77:13)
在ReadStream.emit(events.js:169:7)
在readableAddChunk(_stream_readable.js:146:16)
在ReadStream.Readable.push(_stream_Readable.js:110:10)
在TTY.onread(net.js:523:20)
为什么会发生这种错误
如何只允许某些字符或至少不允许崩溃?读取字符的正确方法是
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write('data: ' + chunk);
}
});
从
发生此错误的原因是键可能“未定义”,并且不包含属性名。已修复
我没有检查键
对象是否存在……例如:
if (key && key.name == 'x') {
console.log('Goodbye!');
process.exit();
}