发布于 2020-01-15 11:21:53
转换流上的常见实现如下所示:
ES5语法
const { Transform } = require('stream');
const util = require('util');
function MyTransform(options) {
if (!(this instanceof MyTransform))
return new MyTransform(options);
Transform.call(this, options);
}
util.inherits(MyTransform, Transform);
MyTransform.prototype._transform = function (chunk, enc, cb) {
// do some data transformation
this.push(chunk);
cb();
};ES6语法
const { Transform } = require('stream');
class MyTransform extends Transform {
constructor(options) {
super(options);
}
_transform(chunk, encoding, cb) {
// do some data transformation
this.push(chunk)
cb()
}
}如您所见,要实现转换流,必须编写一些样板代码,例如扩展转换接口等。
通过使用through2,您只需编写转换函数。利润。
发布于 2021-05-03 12:51:00
在through2文档中,它还说(现在):
自从Node.js引入简化流构造以来,through2的许多应用都变得冗余。
然后,上述Rezvan的例子将成为:
const { Transform } = require('stream');
return new Transform({
transform(chunk, encoding, cb) {
// do some data transformation
this.push(chunk);
cb();
}
});https://stackoverflow.com/questions/58745695
复制相似问题