node.js - 如何在发送前修改文件(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();
}
}
解决方案
字符串示例
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;
推荐阅读
- json - vb .net 获取json信息
- mysql - 无法从 Python 2.7 连接 MySQL。(无法连接到本地主机)
- reactjs - ReactJS i18n 库实现问题
- git - 使用非贡献者帐户推送
- c++ - 包含唯一指针容器作为成员的类是否只能存储在相同类型的容器中?
- php - 通过 PHP 数组对 CSV 数据进行排序
- git - WinMerge difftool 仅在 AppData 临时文件中进行更改,而不在实际文件中进行更改
- oracle - 获取 fetch 返回超过请求的行数错误
- c++ - 为什么callbak函数存在?
- html - 如何使用 flexbox 将 div 放置在标题顶部?