首页 > 解决方案 > 如何在发送前修改文件(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 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();
  }
}

标签: node.jsexpressfileserver

解决方案


字符串示例

  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;

推荐阅读