Skip to content

Instantly share code, notes, and snippets.

@luelista
Last active December 14, 2015 03:18
Show Gist options
  • Save luelista/5019571 to your computer and use it in GitHub Desktop.
Save luelista/5019571 to your computer and use it in GitHub Desktop.
/**
* By TooTallNate, originally posted at https://gist.github.com/1785026
* A quick little thingy that takes a Stream instance and makes
* it emit 'line' events when a newline is encountered.
* Modified by Max Weller to accept custom line feed characters (e.g. \r\n)
*
* Usage:
* ‾‾‾‾‾
* var emitLines = require('./emitLines');
* emitLines(process.stdin, "\n")
* process.stdin.resume()
* process.stdin.setEncoding('utf8')
* process.stdin.on('line', function (line) {
* console.log(line event:', line)
* })
*
*/
function emitLines (stream, lineFeedChar) {
var backlog = ''
stream.on('data', function (data) {
console.log("data in "+data.length+" bytes");
backlog += data
var n = backlog.indexOf(lineFeedChar)
// got a \n? emit one or more 'line' events
while (~n) {
stream.emit('line', backlog.substring(0, n))
backlog = backlog.substring(n + lineFeedChar.length)
n = backlog.indexOf(lineFeedChar)
}
})
stream.on('end', function () {
if (backlog) {
stream.emit('line', backlog)
}
})
}
module.exports = emitLines;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment