replServer.defineCommand(keyword, cmd)
- 
keyword<string> 命令关键字(没有前导.字符)。¥ keyword<string> The command keyword (without a leading.character).
- 
cmd<Object> | <Function> 当处理命令时调用的函数。¥ cmd<Object> | <Function> The function to invoke when the command is processed.
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时显示的帮助文本(可选)。¥ help<string> Help text to be displayed when.helpis entered (Optional).
- 
action<Function> 要执行的函数,可选择接受单个字符串参数。¥ action<Function> The function to execute, optionally accepting a single string argument.
以下示例显示了添加到 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!