replServer.defineCommand(keyword, cmd)


replServer.defineCommand() 方法用于向 REPL 实例添加新的以 . 为前缀的命令。 此类命令是通过键入 . 后跟 keyword 来调用的。 cmd 是具有以下属性的 FunctionObject

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

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

const repl = require('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 实例中使用新命令:

> .sayhello Node.js User
Hello, Node.js User!
> .saybye
Goodbye!
  • keyword <string> The command keyword (without a leading . character).
  • cmd <Object> | <Function> The function to invoke when the command is processed.

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 text to be displayed when .help is entered (Optional).
  • action <Function> The function to execute, optionally accepting a single string argument.

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

const repl = require('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();
});

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

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