How to suggest files with tab completion using readline?

醉酒当歌 提交于 2019-12-12 10:45:08

问题


Within the Bash shell, I can use tab-completion to use suggest file and directory names. How can I achieve this with nodejs and readline?

Examples:

  • /<Tab> should suggest /root/, /bin/, etc.
  • /et<Tab> should complete to /etc/.
  • fo<Tab> should complete to foobar assuming such a file exists in the current directory.

I was thinking of using globbing (pattern search_term.replace(/[?*]/g, "\\$&") + "*"), but is there maybe a library that I have overlooked?

This is my current approach using glob, it is broken when using //<Tab> as it returns the canonicalized name and has possibly some other oddities:

function command_completion(line) {
    var hits;
    // likely broken, one does not simply escape a glob char
    var pat = line.replace(/[?*]/g, "\\$&") + "*";
    // depends: glob >= 3.0
    var glob = require("glob").sync;
    hits = glob(pat, {
        silent: true,
        nobrace: true,
        noglobstar: true,
        noext: true,
        nocomment: true,
        nonegate: true
    });

    return [hits, line];
}

var readline = require("readline");
rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    completer: command_completion
});
rl.prompt();

回答1:


Maybe you could take a look on readdir: https://www.npmjs.com/package/readdir

Just read the directory on which the user is making a tab, then compare the user input with the beginning of each file on the directory and if a filename match, display it to the user. Something like:

var readDir = require('readdir');

function strncmp(str1, str2, lgth) {
  var s1 = (str1 + '')
    .substr(0, lgth);
  var s2 = (str2 + '')
    .substr(0, lgth);

  return ((s1 == s2) ? 0 : ((s1 > s2) ? 1 : -1));
}

var userInput = // get user input;
var path = // get the path;
readDir.read(path, [*], function(err, files) {
    for (var i = 0; i < files.length; i++)
        if (strncmp(files[i], userInput, userInput.length) == 0)
            console.log(files[i]);
});


来源:https://stackoverflow.com/questions/16068607/how-to-suggest-files-with-tab-completion-using-readline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!