Skip to content

Instantly share code, notes, and snippets.

@seanjensengrey
Created March 21, 2014 20:04
Show Gist options
  • Save seanjensengrey/9695169 to your computer and use it in GitHub Desktop.
Save seanjensengrey/9695169 to your computer and use it in GitHub Desktop.
async read of a file
/* open a file and print its contents */
var fs = require('fs');
var cat_file = function(path,stream,completion_callback) {
fs.open(path,'rs',function(err,fd) {
var buf_size = 4096;
var buf = new Buffer(buf_size);
var read_file_bytes = function (fd,pos) {
fs.read(fd,buf,0,buf_size,pos,function(err,bytesRead,buf) {
if (bytesRead === 0) {
completion_callback(fd);
} else {
stream.write(buf.toString('utf8',0,bytesRead));
read_file_bytes(fd,pos+bytesRead);
}
});
}
read_file_bytes(fd, 0);
// this was my problem, it actually told me so!
// fs.closeSync(fd);
});
}
cat_file("1-cat.js",process.stdout,function(fd) {
console.log(fd);
console.log("done catting file!!");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment