replServer.defineCommand(keyword, cmd)


replServer.defineCommand() 方法用于向 REPL 实例添加新的以 . 开头的命令。这类命令通过输入 . 加上 keyword 来调用。cmd 可以是一个 Function 或一个具有以下属性的 Object

【The replServer.defineCommand() method is used to add new .-prefixed commands to the REPL instance. Such commands are invoked by typing a . followed by the keyword. The cmd is either a Function or an Object with the following properties:】

  • help <string> 当输入 .help 时显示的帮助文本(可选)。
  • action <Function> 要执行的函数,可选择性地接受一个字符串参数。

以下示例显示了添加到 REPL 实例的两个新命令:

【The following example shows two new commands added to the REPL instance:】

import repl from 'node:repl';

const replServer = repl.start({ prompt: '> ' });
replServer.defineCommand('sayhello', {
  help: 'Say hello',
  action(name) {
    this.clearBufferedCommand();
    console.log(`Hello, ${name}!`);
    this.displayPrompt();
  },
});
replServer.defineCommand('saybye', function saybye() {
  console.log('Goodbye!');
  this.close();
});const repl = require('node:repl');

const replServer = repl.start({ prompt: '> ' });
replServer.defineCommand('sayhello', {
  help: 'Say hello',
  action(name) {
    this.clearBufferedCommand();
    console.log(`Hello, ${name}!`);
    this.displayPrompt();
  },
});
replServer.defineCommand('saybye', function saybye() {
  console.log('Goodbye!');
  this.close();
});

然后可以在 REPL 实例中使用新命令:

【The new commands can then be used from within the REPL instance:】

> .sayhello Node.js User
Hello, Node.js User!
> .saybye
Goodbye!