Reputation: 1658
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?
Upvotes: 10
Views: 13233
Reputation: 1217
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);
Upvotes: 2
Reputation: 15003
There's no native functionality in node for doing this. You might search around a bit to see if there are third-party libraries for it. If there aren't, it's possible, if a bit tedious, to write your own module that will do it, since any class that implements all the methods and properties listed in the documentation for Stream
and emits and responds to all the events listed in the documentation is, by definition, a Stream
and can be used anywhere that node's built-in Stream
s can.
Upvotes: 1