當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。