Skip to content

Instantly share code, notes, and snippets.

@tj
Created October 30, 2012 05:08
Show Gist options
  • Save tj/3978418 to your computer and use it in GitHub Desktop.
Save tj/3978418 to your computer and use it in GitHub Desktop.
Stream example
var fs = require('fs')
function cat(file) {
var stream = fs.createReadStream(file)
stream.setEncoding('utf8')
return function(write){
stream.on('error', write)
stream.on('data', function(d){ write(null, d) })
stream.on('end', write)
}
}
function uppercase(read) {
return function(write){
read(function(err, str){
if (err) write(err)
else if (str) write(null, str.toUpperCase())
else write()
})
}
}
function buffer(read) {
var buf = ''
return function(write){
read(function(err, str){
if (err) write(err)
else if (str) buf += str
else write(null, buf)
})
}
}
var read = buffer(uppercase(cat('petss.txt')))
read(function(err, buf){
if (err) {
console.error(err.stack);
} else {
console.log(buf);
}
})
@tj
Copy link
Author

tj commented Nov 7, 2012

hmm yeah looks kinda lame with error propagation

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