我有以下Parser:
function Parser(options) { options = options || {}; // options.objectMode = true; options.encoding = 'utf8'; Transform.call(this, options); this._rawHeader = []; this.header = null; } util.inherits(Parser, Transform); Parser.prototype._transform = function(data, encoding, done) { this.push(this._parseRow(data)); done(); }; // Parse a data row into an object Parser.prototype._parseRow = function(row) { var fields = row.split(";"); var obj = { code: fields[0], name: fields[1].trim() }; return obj.toString(); }; var parser = new Parser({}); // Pipe the streams process.stdin .pipe(parser) .pipe(process.stdout);
但是,我明白了:
ACARIT21012;CASSA RURA has no method 'split' at Parser._parseRow (/Users/pmu/projects/b/s/lib/parser.js:38:20) at Parser._transform (/Users/pmu/projects/b/s/lib/parser.js:32:18) at Parser.Transform._read (_stream_transform.js:179:10) at Parser.Transform._write (_stream_transform.js:167:12) at doWrite (_stream_writable.js:219:10) at writeOrBuffer (_stream_writable.js:209:5) at Parser.Writable.write (_stream_writable.js:180:11) at write (_stream_readable.js:573:24) at flow (_stream_readable.js:582:7) at Socket.pipeOnReadable (_stream_readable.js:614:5)
我怀疑流已损坏,但不确定如何防止这种情况发生
答案 0 :(得分:2)
传递给Readable
信息流的数据是Buffer
个对象,而不是String
。 Buffer
没有split
方法。您必须手动调用数据toString()
才能将其作为String
进行操作。
Parser.prototype._transform = function(data, encoding, done) {
this.push(this._parseRow(data.toString()));
done();
};