Reputation: 161
I'm creating a cmd program in Node.js that receives user input and one of those inputs is a folder.
Now I want to make it easier for the user to choose a folder (like the cmd autocompletion for files when using commands such as 'cd'), rather than actually type the whole path.
Is there any best practice for doing that?
Thanks in advance!
Upvotes: 2
Views: 1121
Reputation: 161
Ok, so after looking at what jiyinyiyong answered I was able to get what I wanted.
Basically this is it:
var readline = require('readline');
var fs = require('fs');
function completer(line) {
var currAddedDir = (line.indexOf('/') != - 1) ? line.substring(0, line.lastIndexOf('/') + 1) : '';
var currAddingDir = line.substr(line.lastIndexOf('/') + 1);
var path = __dirname + '/' + currAddedDir;
var completions = fs.readdirSync(path);
var hits = completions.filter(function(c) { return c.indexOf(currAddingDir) === 0});
var strike = [];
if (hits.length === 1) strike.push(currAddedPath + hits[0] + '/');
return (strike.length) ? [strike, line] : [hits.length ? hits : completions, line];
}
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
completer: completer
});
rl.question('whatever', function(answer) {
// Do what ever
});
Upvotes: 1
Reputation: 4713
I saw someone implemented that in cofmon
before. So these links can helpful:
Upvotes: 1