Search code examples
node.jsexpresspipefilestream

changing content of fs.createReadstream


I have requirement such that I am reading a file on express request as follows:

const fs = require('fs');
const os = require('os');
const path = require('path');
var express = require("express");
app = express();

app.get('/getdata', function (req, res) {
  var stream = fs.createReadStream('myFileLocation');// this location contains encrypted file
  let tempVariable = [];
  stream.on('data', function(chunk) {
        tempVariable += chunk;
    });
stream.on('end', function () {
    *****here I read tempVariable and using it I decrypt the file content and output a buffer (say,finalBuffer)****

})
stream.on('error', function (error) {
        res.writeHead(404, 'Not Found');
        res.end();
    });
stream.pipe(res);

So what should I do to make the 'finalBuffer' readable on request,in other words, how to pipe the finalBuffer data with res(response).


Solution

  • Finally I got the way for creating read stream from a Buffer using stream of node js. I got exact solution from here. I have just put a little bit code like

    const fs = require('fs');
    const os = require('os');
    const path = require('path');
    var express = require("express");
    app = express();
    
    app.get('/getdata', function (req, res) { // getdata means getting decrypted data
    
    
    fs.readFile(file_location, function read(err, data) {
       // here I am performing my decryption logic which gives output say 
       //"decryptedBuffer"
       var stream = require("./index.js");
       stream.createReadStream(decryptedBuffer).pipe(res);
    
    })
    })
    
    // index.js
    'use strict';
    
    var util = require('util');
    var stream = require('stream');
    
    module.exports.createReadStream = function (object, options) {
      return new MultiStream (object, options);
    };
    
    var MultiStream = function (object, options) {
      if (object instanceof Buffer || typeof object === 'string') {
        options = options || {};
        stream.Readable.call(this, {
          highWaterMark: options.highWaterMark,
          encoding: options.encoding
        });
      } else {
        stream.Readable.call(this, { objectMode: true });
      }
      this._object = object;
    };
    
    util.inherits(MultiStream, stream.Readable);
    
    MultiStream.prototype._read = function () {
      this.push(this._object);
      this._object = null;
    };
    

    If anybody has some issue with this please comment I will try my best to make him/her understood my code snippet.