【发布时间】: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