Skip to content

Instantly share code, notes, and snippets.

@rcrowley
Last active December 25, 2015 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcrowley/6888979 to your computer and use it in GitHub Desktop.
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.
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