我正在使用 fs.createReadStream()
读取文件,然后将它们通过管道传输到响应。
我想在提供 HTML 文件时添加一个小的 Javascript 函数。
我能想到的唯一方法是将文件读入字符串,将文本附加到字符串,然后将字符串流式传输到响应,但我认为可能有更好/更快的方法来做到这一点。
有没有办法让我随时将文本附加到文件中?
最佳答案
在 @Matthew Bakaitis 建议使用 through
并阅读了一段时间相关内容并检查 github 上的问题后,我发现 through
的开发人员推荐 through2
对于与我类似的情况。
使用 finish
回调更好地实现
let str_to_append="Whatever you want to append"
let through_opts = { "decodeStrings": false, "encoding": "utf8" }
let chunk_handler = function (chunk, enc, next) {
next(null, chunk)
}
let finish_handler = function (done) {
this.push(str_to_append)
done()
}
let through_stream = through2.ctor(through_opts, chunk_handler, finish_handler)
旧实现
这就是我实现解决方案的方式:
var through2 = require("through2");
var jsfn="<script>function JSfn(){ return "this is a js fn";}</script>";
var flag=0;
fileStream.pipe(
through2( {"decodeStrings" : false, "encoding": "utf8"},function(chunk, enc) {
if(flag===0) {
var tempChunk=chunk;
chunk=jsfn;
chunk+=tempChunk;
flag=1;
}
this.push(chunk);
})
).pipe(res);
选项decodeStrings
必须设置为false
,以便数据 block 是字符串而不是缓冲区。这与stream
api的transform
函数有关,与through2无关。
有关 transform
的更多信息
关于javascript - 随时随地将文本附加到 Node.js 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27426081/