gpt4 book ai didi

node.js - 如何使用 readline 建议带有制表符完成的文件?

转载 作者:搜寻专家 更新时间:2023-10-31 22:35:47 24 4
gpt4 key购买 nike

在 Bash shell 中,我可以使用制表符完成来使用建议的文件和目录名称。如何使用 nodejs 和 readline 实现此目的?

例子:

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

我正在考虑使用 globbing(模式 search_term.replace(/[?*]/g, "\\$&") + "*"),但是否有我忽略的库?

这是我目前使用 glob 的方法,在使用 //<Tab> 时它被破坏了因为它返回规范化的名称并且可能还有其他一些奇怪的地方:

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

最佳答案

这是一个有一些怪癖的可行解决方案:

  • 不支持相对路径
  • 尝试按两次 Tab 键显示建议时,它会在建议列表中显示完整路径。
  • 它更喜欢 '/' 而不是 '\',但容忍 Windows 上的 '\' 分隔符
  • 它只支持目录和文件。 (没有设备、管道、套接字、软链接(soft link))

代码:

const { promises: fsPromises } = require("fs"); 
const { parse, sep } = require("path");

function fileSystemCompleter(line, callback) {
let { dir, base } = parse(line);
fsPromises.readdir(dir, { withFileTypes: true })
.then((dirEntries) => {
// for an exact match that is a directory, read the contents of the directory
if (dirEntries.find((entry) => entry.name === base && entry.isDirectory())) {
dir = dir === "/" || dir === sep ? `${dir}${base}` : `${dir}/${base}`;
return fsPromises.readdir(dir, { withFileTypes: true })
}
return dirEntries.filter((entry) => entry.name.startsWith(base));
})
.then((matchingEntries) => {
if (dir === sep || dir === "/") {
dir = "";
}
const hits = matchingEntries
.filter((entry) => entry.isFile() || entry.isDirectory())
.map((entry) => `${dir}/${entry.name}${entry.isDirectory() && !entry.name.endsWith("/") ? "/" : ""}`);
callback(null, [hits, line]);
})
.catch(() => (callback(null, [[], line])));
}

关于node.js - 如何使用 readline 建议带有制表符完成的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16068607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com