我在node.js中寻找这个功能,但没有找到。
我可以自己实施吗?据我所知,node.js在启动时不会加载任何文件(就像Bash对.bashrc
所做的那样(,我也没有注意到有任何方法可以以某种方式覆盖shell提示。
有没有一种方法可以在不编写自定义shell的情况下实现它?
您可以对REPL进行猴子补丁。请注意,必须使用completer
的回调版本,否则它将无法正常工作:
var repl = require('repl').start()
var _completer = repl.completer.bind(repl)
repl.completer = function(line, cb) {
// ...
_completer(line, cb)
}
仅作为引用。
readline
模块具有readline.createInterface(options)
方法,该方法接受用于完成选项卡的可选completer
函数。
function completer(line) {
var completions = '.help .error .exit .quit .q'.split(' ')
var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })
// show all completions if none found
return [hits.length ? hits : completions, line]
}
和
function completer(linePartial, callback) {
callback(null, [['123'], linePartial]);
}
链接到api文档:http://nodejs.org/api/readline.html#readline_readline_createinterface_options
您可以使用下面的completer函数来实现选项卡功能。
const readline = require('readline');
/*
* This function returns an array of matched strings that starts with given
* line, if there is not matched string then it return all the options
*/
var autoComplete = function completer(line) {
const completions = 'var const readline console globalObject'.split(' ');
const hits = completions.filter((c) => c.startsWith(line));
// show all completions if none found
return [hits.length ? hits : completions, line];
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
completer: autoComplete
});
rl.setPrompt("Type some character and press Tab key for auto completion....n");
rl.prompt();
rl.on('line', (data) => {
console.log(`Received: ${data}`);
});
参考:https://self-learning-java-tutorial.blogspot.com/2018/10/nodejs-readlinecreateinterfaceoptions_2.html