var readline = require('readline'); var prefix = '> '; var rl = readline.createInterface({ input: process.stdin, output: process.stdout, completer: function(line) {//按Tab键,自动提示 var completions = 'hello exit bye quit'.split(' ') var hits = completions.filter(function(c) { if (c.indexOf(line) == 0) { return c; } }); return [hits && hits.length ? hits : completions, line]; }, terminal: true }); var name; rl.on('line', function(line) {//响应输入 switch(line.trim()) { case 'hello': console.log('hello ' + name); break; case 'exit': case 'quit': case 'bye': rl.close(); break; default: console.log('Say what? I might have heard `' + line.trim() + '`'); break; } rl.prompt(true); }).on('SIGINT', function() {//响应Ctrl + C rl.question('Sure to exit ? ', function(answer) { if (answer.match(/^y(es)?$/i)) { rl.close(); }else { rl.prompt(true); } }); }).on('close', function() {//响应退出 console.log('Bye! Have a good day!'); process.exit(0); }); rl.setPrompt(prefix); rl.prompt(true); rl.question('What is your name?', function(answer) { console.log('welcome you, ' + answer); name = answer; rl.prompt(true); });