示例:Tiny CLI

这里有一个如何使用所有这些接口一起来创建一个小型命令行界面的示例:

  1. const readline = require('readline');
  2. const rl = readline.createInterface(process.stdin, process.stdout);
  3. rl.setPrompt('OHAI> ');
  4. rl.prompt();
  5. rl.on('line', (line) => {
  6. switch (line.trim()) {
  7. case 'hello':
  8. console.log('world!');
  9. break;
  10. default:
  11. console.log('Say what? I might have heard `' + line.trim() + '`');
  12. break;
  13. }
  14. rl.prompt();
  15. }).on('close', () => {
  16. console.log('Have a great day!');
  17. process.exit(0);
  18. });