在 Node v10.11 中,我试图将对象推入管道,但总是出错。
events.js:72 throw er; // Unhandled 'error' event ^ TypeError: Invalid non-string/buffer chunk at validChunk (_stream_writable.js:150:14) at WriteStream.Writable.write (_stream_writable.js:179:12)
我能做到
this.push(chunk)
直接通过管道传输数据,但我做不到
var result = {'the web content is': chunk}
this.push(result)
30 LOC 中的可运行示例:
var stream = require('stream');
var MsgExtractStream = function() {
stream.Transform.call(this,{objectMode: true});
}
MsgExtractStream.prototype = Object.create(
stream.Transform.prototype, {constructor: {value: MsgExtractStream}} )
MsgExtractStream.prototype._transform = function(chunk, encoding, callback) {
var result = {'the website is': chunk};
this.push(result);
}
MsgExtractStream.prototype.write = function () {
this._transform.apply(this, arguments);
};
MsgExtractStream.prototype.end = function () {
this._transform.apply(this, arguments);
this.emit("end");
};
var fs = require("fs"),
inPage = fs.createReadStream("inPage.html"),
outPage = fs.createWriteStream("outPage.html"),
msgPage = new MsgExtractStream();
inPage.
pipe(msgPage).
pipe(outPage);