如何使用readline建议带有制表符补全的文件? [英] How to suggest files with tab completion using readline?

查看:199
本文介绍了如何使用readline建议带有制表符补全的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bash shell中,我可以使用制表符补全来使用建议的文件名和目录名.如何使用nodejs和 readline 实现此目标?

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?

示例:

  • /<Tab>应建议/root//bin/
  • /et<Tab>应该完成到/etc/.
  • 假设当前目录中存在这样的文件,
  • fo<Tab>应该完成到foobar.
  • /<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.

我当时正在考虑使用遍历(模式search_term.replace(/[?*]/g, "\\$&") + "*"),但是也许我忽略了一个库吗?

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

这是我目前使用glob的方法,在使用//<Tab>时会损坏,因为它返回规范化的名称,并且可能还有其他奇怪之处:<​​/p>

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

推荐答案

也许您可以看一下readdir: https://www.npmjs.com/package/readdir

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

这篇关于如何使用readline建议带有制表符补全的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆