【问题标题】:changing content of fs.createReadstream改变 fs.createReadstream 的内容
【发布时间】:2020-03-25 05:49:41
【问题描述】:

我有这样的要求,即我正在阅读以下明确要求的文件:

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(响应)来传递 finalBuffer 数据。

【问题讨论】:

  • 如果您想使用流,那么您将创建一个流转换,以增量方式解密数据。这将允许您将其通过管道传递给响应。按照您现在的方式,当您到达end 事件时,内容已经发送。这是good article

标签: node.js express pipe filestream


【解决方案1】:

最后我找到了使用节点 js 流从缓冲区创建读取流的方法。 我从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;
};

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2014-08-20
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多