当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js REPLServer.defineCommand(keyword, cmd)用法及代码示例

replServer.defineCommand(keyword, cmd)

添加于:v0.3.0

参数

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

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

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

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 实例中使用新命令:

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

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 REPLServer.defineCommand(keyword, cmd)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。