【问题标题】:How to modify file before sending (Node js)如何在发送前修改文件(Node js)
【发布时间】:2020-05-26 19:48:49
【问题描述】:

我有一个 nodejs 应用程序,它从路径发送请求的文件,我想在发送之前修改和更新“src”和“href”标签,我正在使用 res.sendFile("path to file") 但我想在发送前修改这个文件,有什么办法可以做到这一点

Router.get("/report/", (req, res) => {
  const path = req.query.drive + req.query.file;

  const options = {
    project: req.query.project,
    type: "static_analysis_report1"
  };

  fs.createReadStream(path)
    .pipe(new ModifyFile(options))
    .pipe(res);
});

修改文件类

class ModifyFile extends Transform {
  project_name = "";
  type = "";

  constructor(options) {
    super(options);
    this.project_name = options.project_name;
    this.type = options.type;
  }

  _transform(chunk, encoding, cb) {
    const project_name = this.project_name;
    const type = this.type;

    var htmlCode = chunk.toString();
    console.log(htmlCode);
    cb();
  }
}

【问题讨论】:

  • 你可以为它创建Trasform流,代码就像fs.createReadStream(filename).pipe(new MyTransform()).pipe(res);
  • 你能告诉我会有什么反应吗? (即 res),我是否将其包含在我的 Router.get() 中??
  • const { Transform } = require('stream'); const { createReadStream } = require('fs'); const myTransform = new Transform({ transform(chunk, encoding, callback) { this.push(chunk); // <--- modify it callback(); } }); app.get('/', function(req, res) { createReadStream('some file').pipe(myTransform).pipe(res); });
  • 非常感谢,但还有一个问题,如何将修改后的文件发回??

标签: node.js express fileserver


【解决方案1】:

字符串示例

  import Express from 'express';
  import path from 'path';
  import { readFile } from 'fs';
  import util from 'util';
  
  const readFileAsync = util.promisify(readFile);
  const app = new Express();
  
  app.get('/file/url', async (req, res) => {
    let index = await readFileAsync(path.join(__dirname, 'index.html'), 'utf8');
   
    index = index.replace('SOMETHING', 'SOMETHING ELSE'); //MODIFY THE FILE AS A STRING HERE
    return res.send(index);
  });
  
  export default app;

【讨论】:

    【解决方案2】:

    基于流的示例

    const { Transform } = require('stream');
    const  { createReadStream } = require('fs');
    const {join} = require('path');
    
    const myTransform = new Transform({
      transform(chunk, encoding, callback) {
         this.push(chunk); // <--- modify it
         callback();
      }
    });
    
    app.get('/:file', function(req, res) {
          createReadStream(join(__dirname, req.params.file)).pipe(myTransform).pipe(res);
    });
    

    【讨论】:

    • 我想要一个来自 req.query.project 的值,如何在 myTransform 中访问它??
    • 只需将我的 Transformer 创建为类,而不是实例,并在每个请求上创建新实例。在这种情况下,您可以通过构造函数传递任何参数。 nodejs.org/api/stream.html#stream_new_stream_transform_options
    • 很抱歉打扰您,但我将如何结束请求??
    • 在文件结束时自动关闭管道
    • 我没有收到文件作为响应
    【解决方案3】:

    之前使用回调或承诺更新数据。

    【讨论】:

      猜你喜欢
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 2013-11-24
      • 1970-01-01
      • 2019-11-22
      相关资源
      最近更新 更多