Node.js Standard Input


Commands will be provided to our shell through the process' standard input. By default, Node.js does not activate the standard input stream. The first thing we will do is enable standard input and echo back what we read.

Create a new file called standardInput.js in a brand new directory and add the following:

process.stdin.on('data', function (input) {
	console.log(input.toString());
});

input is buffer object. That's because the input variable passed in to our function (input) { ... } callback does not contain the string value of your input directly.

Calling input.toString() will create a new JavaScript string containing the entire contents of the Buffer. An optional encoding can be specified as the first argument of the toStringfunction (for example, input.toString('utf8')). Since we're working with relatively short strings, let's go ahead and call input.toString() on the Buffer object.

Now starting up the js using Node command and typing any value will result in the expected output ending with the new line character. The next step is to trim and parse the input string. The commands in our simple shell will take the form:

Node JS standard Input

We can use a handy regular expression to separate the arguments from the command: /(\w+)(.*)/. We will then parse our arguments by splitting on white space.

process.stdin.on('data', function (input) {
	var matches = input.toString().match(/(\w+)(.*)/);
	//console.log(matches);
	var args = matches[0].trim().split(/\s+/);
	console.log(args);
});

Node JS Input arguments


The result of 'some string'.split(/\s+/) is an array ['some', 'string']. This example could have been done with 'some string'.split(' '), except that would not account for other types of white space or multiple white space characters.

For example: 'some string'.split(' ') would result in ['some', '', 'string']. Feel free to check out the result of the above code block by logging out the value of command and args. You may want to add a little more logic to make this resilient to malformed input. We will leave that exercise up to you.