我正在使用Transform Streams,但是当我尝试将流附加到多个文件时,我收到错误。
var T = new Transform;
T._transform = function (chunk, encoding, done) {
T.push(encoding);
done();
}
co( function *() {
console.log('good');
let files = yield fs.readdir(PATH);
for ( let f = 0; f<files.length; f++ ) {
console.log(files[f]);
fs_old.createReadStream(PATH + '/' + files[f], {encoding: 'UTF-8'} ).pipe(Object.create(T)).pipe(fs_old.createWriteStream('out'));
}
} )();
我得到的是,
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Trace
at Transform.EventEmitter.addListener (events.js:176:15)
at Transform.Readable.on (_stream_readable.js:664:33)
at ReadStream.Readable.pipe (_stream_readable.js:488:8)
at /home/ecarroll/code/chrome-okc-plugin/test.js:37:72
at GeneratorFunctionPrototype.next (native)
at next (/home/ecarroll/code/chrome-okc-plugin/node_modules/co/index.js:70:21)
at /home/ecarroll/code/chrome-okc-plugin/node_modules/co/index.js:89:18
at /home/ecarroll/code/chrome-okc-plugin/node_modules/thunkify/index.js:28:12
at Object.oncomplete (fs.js:97:15)
我如何复制转换流,以便我可以在多个文件上运行它。
答案 0 :(得分:2)
首先 - 这不是错误,而是一个警告。有时可以看到这个,但在这种情况下不是。您需要具有不同的转换流。 Object.create
不会克隆对象,它会创建一个具有给定原型的对象,因此所有函数和数据实际上都是共享的(效果与传递T
相同)。你需要使用这样的函数:
function createTransform () {
var T = new Transform;
T._transform = function (chunk, encoding, done) {
T.push(encoding);
done();
}
return T;
}
您所做的是创建单个流,这通常是在缩写文档中完成的。这不会为每个文件创建一个新的流......上面会这样做,但它是通过修改新的Transform对象来实现的。或者,您可以继承Transform,
function MyTransform (options) {
// this is needed only so you can handle calls to MyTransform()
// rather than `new MyTransform()`
// (makes `this` in _transform point to stream)
if (!(this instanceof MyTransform))
return new MyTransform(options);
Transform.call(this, options)
}
// make sure this comes before BEFORE you subclass the prototype
util.inherits(MyTransform, Transform);
MyTransform.prototype._transform = function (chunk, encoding, done) {
this.push(chunk, encoding);
done();
}