NodeJS:2021 年干预 Steam 的“through2”的实际原生替代品

Gur*_*ofu 3 node.js through2

来自through2文档:

\n
\n

你需要这个吗?

\n

自从 Node.js 引入了简化流构造以来,\nthrough2 的许多使用都变得多余了。考虑您是否确实需要\n使用 through2 还是只想使用\'readable-stream\' 包或\n核心\'stream\' 包(源自\'readable-stream\')。

\n
\n

如果我理解正确的话,现在(从 2021 年开始)我们可以在没有第三方库的情况下干预流。\n我没有找到如何执行与Stream 文档through2中相同的操作。

\n
// ...\n  .pipe(through2(function (file, encoding, callback) {\n    // Do something with file ...\n    callback(null, file)\n   }))\n\n// \xe2\x86\x91 Possible to reach the same effect natively (with core packages)?\n
Run Code Online (Sandbox Code Playgroud)\n

我想,2021 年一定会有一些支持 async/await 语法的方法:

\n
// ...\n  .pipe(newFeatureOfModernNodeJS(async function (file) {\n\n    await doSomethingAsyncWithFile(file);\n    // on fail - same effect as "callback(new Error(\'...\'))" of trough2\n\n    return file; // same effect as "callback(null, file)" of trough2\n\n    // or\n    return null; // same effect as `callback()` of trough2\n   }))\n\n// \xe2\x86\x91 Possible to reach the same effect natively (with core packages)?\n
Run Code Online (Sandbox Code Playgroud)\n

Rob*_*dle 5

您正在寻找的可能是 Transform 流,它是由 Node.js 附带的本机“流”库实现的。我还不知道是否有异步兼容版本,但肯定有基于回调的版本。您需要继承本机 Transform 流并实现您的功能。

这是我喜欢使用的样板:

const Transform = require('stream').Transform;
const util      = require('util');

function TransformStream(transformFunction) {
  // Set the objectMode flag here if you're planning to iterate through a set of objects rather than bytes
  Transform.call(this, { objectMode: true });
  this.transformFunction = transformFunction;
}

util.inherits(TransformStream, Transform);

TransformStream.prototype._transform = function(obj, enc, done) {
  return this.transformFunction(this, obj, done);
};

module.exports = TransformStream;
Run Code Online (Sandbox Code Playgroud)

现在您可以在需要使用的地方使用它:

const TransformStream = require('path/to/myTransformStream.js');
//...
.pipe(new TransformStream((function (file, encoding, callback) {
    // Do something with file ...
    callback(null, file)
 }))
Run Code Online (Sandbox Code Playgroud)