Skip to content

Instantly share code, notes, and snippets.

@tj
Created October 30, 2012 05:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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);
}
})
@dominictarr
Copy link

hey, this looks pretty good, but what happens if 'pets.txt' doesn't exist? or it errors part way through?

@tj
Copy link
Author

tj commented Nov 7, 2012

I left out error stuff for brevity, I guess we'd have to do the traditional node (err, res) style. Other than lacking .readable and the other props this sort of api might be nice, I haven't fooled around with it in practice yet

@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