Last active
December 25, 2015 00:39
-
-
Save rcrowley/6888979 to your computer and use it in GitHub Desktop.
The things you have to do to process stdin line-by-line in Node.js and it still blows up this process' memory over blocking whatever's connected to stdin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var readline = require('readline') | |
var ch = [] | |
, closed = false | |
, rl = readline.createInterface({ | |
input: process.stdin | |
, output: process.stdout | |
, terminal: false | |
}) | |
rl.on('close', function () { closed = true }) | |
rl.on('error', function (error) { | |
console.error(error) | |
process.exit(1) | |
}) | |
rl.on('line', ch.push.bind(ch)) | |
function work() { | |
var input = ch.shift() | |
if (typeof input === 'undefined') { | |
if (closed) { | |
return | |
} | |
return process.nextTick(work) | |
} | |
asyncWork(input, function (error, output) { | |
if (error) { | |
console.error(error) | |
process.exit(1) | |
} | |
process.stdout.write(output) | |
process.nextTick(work) | |
}) | |
} | |
work() | |
function asyncWork(input, f) { | |
process.nextTick(function () { f(undefined, input.toUpperCase()) }) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment