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