在写入流之前添加转换

Add transform before write stream

我有一个函数,例如

function writeToStream(writeStream) {
  writeStream.write("test\n");
}

如何在写入最终目的地之前应用此转换?注意:我无法控制 writeToStream 函数,我只想对其写入的内容应用转换

const fs = require("fs");
const { Transform } = require("stream");

const upperCaseTr = new Transform({
  transform(chunk, encoding, callback) {
    //this is never called???
    callback(null, chunk.toString().toUpperCase());
  },
});

function writeToStream(writeStream) {
  writeStream.write("test\n");
}

const r = fs.createWriteStream("test.txt");

writeToStream(upperCaseTr.pipe(r));

使用上面的代码,我的自定义转换 upperCaseTr 永远不会被调用

这个答案对解决这个问题很有帮助

具体来说,upperCaseTr.pipe(r) 只是 returns r,因此永远不会调用 upperCaseTr

这是一个使用 through2 的答案,类似于链接的答案

const fs = require("fs");
const through2 = require("through2");

function writeToStream(writeStream) {
  writeStream.write("test test test test test\n");
}

const stream = through2.obj((chunk, enc, callback) => {
  callback(null, chunk.toString().toUpperCase());
});

const out = fs.createWriteStream("test.txt");
stream.pipe(out);

writeToStream(stream);

这是一个使用 Transform 的问题,与我原来的问题更相似

const fs = require("fs");
const { Transform } = require("stream");

function writeToStream(writeStream) {
  writeStream.write("test test test test test\n");
}

const upperCaseTr = new Transform({
  transform(chunk, encoding, callback) {
    callback(null, chunk.toString().toUpperCase());
  },
});

const out = fs.createWriteStream("test.txt");
upperCaseTr.pipe(out);

writeToStream(upperCaseTr);