我正在尝试像这样实现一个同步可写流:
var StreamingFileWriter = /** @class */ (function () {
function StreamingFileWriter(outputfile) {
if (!outputfile) {
throw new Error('Output File Required');
}
this.fileStream = fs.createWriteStream(outputfile, { flags: 'a', highWaterMark: 5000 });
this.out = this.out.bind(this);
this.outLn = this.outLn.bind(this);
this.endAsync = this.endAsync.bind(this);
}
StreamingFileWriter.prototype.out = async function (data) {
if (!this.fileStream.write(data, 'utf-8')) {
await this.drain();
};
};
StreamingFileWriter.prototype.outLn = function (data) {
this.fileStream.write(data + "\n", 'utf-8');
};
StreamingFileWriter.prototype.endAsync = function () {
var _this = this;
this.fileStream.end();
return new Promise(function (resolve, reject) {
_this.fileStream.on('finish', function () {
resolve();
});
_this.fileStream.on('error', function (err) {
reject(err);
});
});
};
StreamingFileWriter.prototype.drain = function () {
let _this = this;
return new Promise((resolve) => _this.fileStream.once('drain', resolve));
}
return StreamingFileWriter;
}());
exports.StreamingFileWriter = StreamingFileWriter;
但是缓冲的数据不会在每次写入调用时写入文件。我已经调整了 highWaterMark 但没有任何价值帮助。如果我调试,我可以看到流需要排空,但等待排空事件不会刷新数据。
我用它来将 JSON 数据写入文件,所以我是这样开始的:
out('[');
它立即将“[”写入文件。然后我执行以下操作:
await out(JSON.stringify(data, null, 2)});
在一个for..of
循环中,但没有一个data
被同步写入文件。endAsync
调用函数时,所有内容都会立即写入