Как определить функцию в приглашении Node.js, без префикса точки? - PullRequest
0 голосов
/ 13 июня 2019

Используя defineCommand, мы можем определить команду, которую можно вызвать, используя точку перед ней:

replServer.defineCommand("foo", ...)

Затем в ответе мы можем сделать:

> .foo

И это вызовет команду, которую мы определили.

Я хотел бы повторить ту же функциональность, что и в отладчике nodejs, чтобы определять команды как функции, вместо использования .keyword.

Используя useGlobal: true, мы можем передать контекст global в REPL, а затем получить доступ к любым глобальным функциям, но мне интересно, есть ли способ добавить их автоматически в вывод справки REPL, как это делает defineCommand.

Как мы можем это сделать?

Вот пример из документов .

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();
});

Вот как вывод справкивыглядит так:

$ node tmp.js                                                                                                                                                      
42                                                                                                                                                                                                          
> .help                                                                                                                                                                                                     
.break      Sometimes you get stuck, this gets you out
.clear      Break, and also clear the local context                 
.editor     Enter editor mode
.exit       Exit the repl
.help       Print this help message
.load       Load JS from a file into the REPL session
.save       Save all evaluated commands in this REPL session to a file
.saybye
.sayhello   Say hello
$ node debug tmp.js
...
debug> help
run, restart, r       Run the application or reconnect
kill                  Kill a running application or disconnect

cont, c               Resume execution
next, n               Continue to next line in current file
step, s               Step into, potentially entering a function
out, o                Step out, leaving the current function
backtrace, bt         Print the current backtrace
...
...