如何在发送前修改文件(Node js)

How to modify file before sending (Node js)

我有一个 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

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

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

基于流的示例

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

字符串示例

  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;