Created
October 30, 2012 05:08
-
-
Save tj/3978418 to your computer and use it in GitHub Desktop.
Stream example
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 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); | |
} | |
}) |
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
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
hey, this looks pretty good, but what happens if 'pets.txt' doesn't exist? or it errors part way through?