Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Create stream from buffer

Tags:

node.js

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?

like image 413
Richeve Bebedor Avatar asked Oct 13 '12 03:10

Richeve Bebedor


1 Answers

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)

Async loading buffer from file

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);


        });
      });
    });
  }
});

Sync Loading buffer from file:

//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);
like image 196
vincentlcy Avatar answered Oct 06 '22 00:10

vincentlcy