I save my file to a buffer and cache the buffer for future use. Now I want to use the buffer to create a stream so that I can pipe it to the response again. Is this possible? and if it is then how?
I found this most promising, thanks to felixge (node committer, esp stream module) https://github.com/felixge/node-combined-stream
Example of piping a file to buffer first then construct a stream and pipe to process std out, modified from the article
(you can pipe from file systems stream directly, here is for illustrate)
var fs = require("fs");
var fileName = "image.jpg";
var CombinedStream = require('combined-stream');
var combinedStream = CombinedStream.create();
fs.exists(fileName, function(exists) {
if (exists) {
fs.stat(fileName, function(error, stats) {
fs.open(fileName, "r", function(error, fd) {
var buffer = new Buffer(stats.size);
fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
fs.close(fd);
//even the file stream closed
combinedStream.append(buffer);
combinedStream.pipe(process.stdout);
});
});
});
}
});
//get buffer
var buffer = readFileSync(fileName);
//or do it yourself
var stats = fs.statSync(fileName);
var buffer = new Buffer(stats.size);
var fd = fs.openSync(fileName,"r");
fs.readSync(fd,buffer,0,buffer.length,null);
fs.close(fd);
combinedStream.append(buffer);
combinedStream.pipe(process.stdout);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With