Say you have a little CLI tool, but you want to be able to prompt a user for additional data after the script has started, rather than passing it in as a command line argument or putting it in a file. To do this, you'll need to listen to STDIN ("standard input", i.e. your keyboard), which Node.js exposes for you as process.stdin.
Basically, streams are Node's way of dealing with evented I/O. The first two readable stream methods you are going to need to know are pause () and resume ().
Try the following example out in a new file;
process.stdin.resume();
process.stdin.setEncoding('utf8');
var util = require('util');
process.stdin.on('data', function (text) {
console.log('received data:', util.inspect(text));
if (text === 'quitn') {
done();
}
});
function done() {
console.log('Now that process.stdin is paused, there is nothing more to do.');
process.exit();
}
If all of this sounds complicated, or if you want a higher-level interface to this sort of thing, there is a module you can use for this is Prompt available on npm.
Just head to your terminal,
Ctrl+Alt+T
and enter the following command:
npm install prompt
Prompt is built to be easy and makes it trivial to handle a certain set of recurring properties that you'd want to attach.
Give it a shot and tell me how it worked in the comments below. Thanks for visiting Base64!