Skip to content

Instantly share code, notes, and snippets.

@touv
Created October 3, 2012 11:50
Show Gist options
  • Save touv/3826541 to your computer and use it in GitHub Desktop.
Save touv/3826541 to your computer and use it in GitHub Desktop.
Split stdin by line with nodejs
#!/usr/bin/env node
process.stdin.resume();
process.stdin.setEncoding('utf8');
var remainder = ''
process.stdin.on('data', function (chunk) {
var lines = chunk.toString().split('\n');
lines.unshift(remainder + lines.shift());
remainder = lines.pop();
lines.forEach(function(line) {
process.stdout.write(line);
process.stdout.write('\n');
});
});
@gerrich
Copy link

gerrich commented Mar 26, 2013

the last "remainder" is not printed out:

$ echo -n "1111" | nodejs splitline.js
$ echo "1111" | nodejs splitline.js
1111
$

One can add the following to fix it:
16: process.stdin.on('end', function() {process.stdout.write(remainder);});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment