Search code examples
node.jsexpressfileserver

How to modify file before sending (Node js)


I have a nodejs application which sends requested files from path, I want to modify and update the "src" & "href" tags before sending them, I'm using res.sendFile("path to file") but I want to modify this file before sending, Is there any way by which I can do that

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

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

Solution

  • Example based on stream

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