我有这个代码:
import * as stream from 'stream';
export class JSONParser extends stream.Transform {
lastLineData = '';
objectMode = true;
constructor() {
super();
}
transform(chunk, encoding, cb) {
let data = String(chunk);
if (this.lastLineData) {
data = this.lastLineData + data;
}
let lines = data.split('\n');
this.lastLineData = lines.splice(lines.length - 1, 1)[0];
lines.forEach(l => {
try {
// l might be an empty string; ignore if so
l && this.push(JSON.parse(l));
}
catch (err) {
// noop
}
});
cb();
}
flush(cb) {
if (this.lastLineData) {
try {
this.push(JSON.parse(this.lastLineData));
}
catch (err) {
// noop
}
}
this.lastLineData = '';
cb();
}
}
问题是TS 类型不能识别(原型)方法。我是否错误地扩展了 Transform 类?
这是问题所在:
请注意,这是正确的:
import * as stream from 'stream';
//////////////////////////////////////////////////
export interface IParsedObject {
[index: string]: any
}
export const createParser = function () {
let lastLineData = '';
return new stream.Transform({
objectMode: true,
transform(chunk: any, encoding: string, cb: Function) {
let data = String(chunk);
if (lastLineData) {
data = lastLineData + data;
}
let lines = data.split('\n');
lastLineData = lines.splice(lines.length - 1, 1)[0];
lines.forEach(l => {
try {
// l might be an empty string; ignore if so
l && this.push(JSON.parse(l));
}
catch (err) {
// noop
}
});
cb();
},
flush(cb: Function) {
if (lastLineData) {
try {
this.push(JSON.parse(lastLineData));
}
catch (err) {
// noop
}
}
lastLineData = '';
cb();
}
});
};
但上面的课程似乎不一样。