Hello everyone! This is the sixth post in my new node.js modules you should know about article series.
The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node, the fourth was about request - the swiss army knife of HTTP streaming, the fifth was about hashish - hash combinators library.
This time I'll introduce you to a brand new module called read. Read was created just yesterday by Isaac Z. Schlueter, the author of npm. Read is basically read(1) for node. You can read input from stdin with it easily.
Here is an example,
var read = require('read');
read({ prompt : 'Username: ' }, function (err, user) {
read({ prompt : 'Password: ', silent : true }, function (err, pass) {
console.log(user, pass);
process.stdin.destroy();
});
})
Nesting functions like this is ugly, so you better use seq, the asynchronous flow combinators library, by James Halliday. (I'll introduce you to this module some time soon.) Here is how it looks with seq:
var read = require('read');
var Seq = require('seq');
Seq()
.seq(function () {
read({ prompt : 'Username: ' }, this.into('user'));
})
.seq(function () {
read({ prompt : 'Password: ', silent : true }, this.into('pass'));
})
.seq(function (pass) {
console.log(this.vars.user, this.vars.pass);
});
Here are all the options read
supports:
prompt - What to write to stdout before reading input. silent - Don't echo the output as the user types it. num - Max number of chars to read from terminal. delim - The char that means we're done. Default: "\n" timeout - Number of ms to wait for user input before giving up.
Note: If silent
is true, or num is set, or delim
is something other than "\n", then read will set raw mode, and read character by character.
You can install read
through npm as always:
npm install read