来自through2文档:
你需要这个吗? 自从Node.js引入简化流构造以来,through2的许多应用都变得冗余。考虑一下您是否真的需要使用through2,还是只想使用“可读-流”包,还是使用核心“流”包(从“可读-流”派生而来)。
如果我理解正确的话,现在(从2021年起)我们可以在没有第三方库的情况下对流进行干预。我没有找到如何做与through2在流文档中相同的事情。
// ...
.pipe(through2(function (file, encoding, callback) {
// Do something with file ...
callback(null, file)
}))
// ↑ Possible to reach the same effect natively (with core packages)?我想,对于2021年,必须有一些支持异步/等待语法的方法:
// ...
.pipe(newFeatureOfModernNodeJS(async function (file) {
await doSomethingAsyncWithFile(file);
// on fail - same effect as "callback(new Error('...'))" of trough2
return file; // same effect as "callback(null, file)" of trough2
// or
return null; // same effect as `callback()` of trough2
}))
// ↑ Possible to reach the same effect natively (with core packages)?发布于 2021-02-10 17:52:31
您要寻找的可能是转换流,这是由Node.js中包含的本机“流”库实现的。我还不知道是否有一个异步兼容的版本,但肯定有一个基于回调的版本。您需要从本机转换流继承并实现您的函数。
这是我喜欢使用的样板:
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;现在,您可以在您可以通过以下方式使用的地方使用它:
const TransformStream = require('path/to/myTransformStream.js');
//...
.pipe(new TransformStream((function (file, encoding, callback) {
// Do something with file ...
callback(null, file)
}))https://stackoverflow.com/questions/66007171
复制相似问题