更改fs.createReadstream的内容

问题描述 投票:0回答:1

我有如下要求,我应按明确的要求阅读文件:

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

所以我应该怎么做才能根据要求使'finalBuffer'可读,换句话说,如何用res(response)传递finalBuffer数据。

node.js express pipe filestream
1个回答
0
投票

最后,我获得了使用节点js流从Buffer创建读取流的方法。我从here获得了确切的解决方案。我刚刚输入了一些代码,例如

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

如果有人对此有任何疑问,请发表评论,我会尽力使他/她理解我的代码片段。

© www.soinside.com 2019 - 2024. All rights reserved.