How to suggest tab completion files with readline?

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

Examples:

  • /<Tab> should offer /root/ , /bin/ etc.
  • /et<Tab> should end before /etc/ .
  • fo<Tab> should end before foobar , assuming that such a file exists in the current directory.

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

This is my current approach using glob, it breaks when using //<Tab> , as it returns a canonical name and may have some other weirdness:

 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(); 
+6
source share
1 answer

Perhaps you can take a look at readdir: https://www.npmjs.com/package/readdir

Just read the directory in which the user makes the tab, then compare the user input to the beginning of each file in the directory and, if the file name matches, display it to the user. Sort of:

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

All Articles