简体   繁体   English

如何在 node.js shell 中实现制表符补全?

[英]How do I implement tab completion in node.js shell?

I was looking for this feature in node.js and I haven't found it.我在 node.js 中寻找这个功能,但我没有找到它。
Can I implement it myself?我可以自己实现吗? As far as I know, node.js doesn't load any file at it's startup (like Bash does with .bashrc ) and I haven't noticed any way to somehow override shell prompt.据我所知, node.js 在启动时不会加载任何文件(就像 Bash 对.bashrc所做的那样),我没有注意到任何方法可以以某种方式覆盖 Z2591C98B70119FE624898B1E424 提示。

Is there a way to implement it without writing custom shell?有没有办法在不编写自定义 shell 的情况下实现它?

You could monkey-patch the REPL.您可以对 REPL 进行猴子补丁。 Note that you must use the callback version of the completer , otherwise it won't work correctly:请注意,您必须使用completer的回调版本,否则将无法正常工作:

var repl = require('repl').start()
var _completer = repl.completer.bind(repl)
repl.completer = function(line, cb) {
  // ...
  _completer(line, cb)
}

Just as a reference.只是作为参考。

readline module has readline.createInterface(options) method that accepts an optional completer function that makes a tab completion. readline模块具有readline.createInterface(options)方法,该方法接受一个可选的completer器 function 来完成制表符。

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]
}

and

function completer(linePartial, callback) {
  callback(null, [['123'], linePartial]);
}

link to the api docs: http://nodejs.org/api/readline.html#readline_readline_createinterface_options链接到 api 文档: http://nodejs.org/api/readline.html#readline_readline_createinterface_options

You can implement tab functionality using completer function like below.您可以使用完成器 function 来实现选项卡功能,如下所示。

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

Reference : https://self-learning-java-tutorial.blogspot.com/2018/10/nodejs-readlinecreateinterfaceoptions_2.html参考https://self-learning-java-tutorial.blogspot.com/2018/10/nodejs-readlinecreateinterfaceoptions_2.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM