假设我有一个对象
logfile是一个实际文件。
wStream = require("stream").Writable
我定义了:
logStream = function logStream () {
this.file = logfile;
wStream.call(this);
};
require("util").inherits(logStream, wStream);
logStream.prototype._write = function logStream_write (data, enc, cb) {
fs.appendFile(this.file, data, 'utf-8', function WatchLogErr(err) {
if (err) {throw Error(err);}
});};
const log = new logStream();
log.on('finish', function () {
console.log("finished writing to log stream");
});
如果我写
log.write("watching changes\n");
log.write("watching changes\n");
它只写一次然后不写。
为什么呢?它过早结束了吗? 如何让它写完而不会结束?
更新
如果我将cb传递给函数,fn(args,cb){//做某事; CB(X);}; 然后我可以在触发fn时定义:fn([1,2,3],shifoo(x){console.log(x);}); 正确的吗?
所以我在哪里使用这个cb? 说
log.write("watching changes2\n", 'utf-8', function (data) {
console.log("wrote " + data.toString());
});
这样做会给我这个错误:
Error: Uncaught, unspecified "error" event.
at Error (native)
at logStream.emit (events.js:87:13)
at onwriteError (_stream_writable.js:317:10)
at onwrite (_stream_writable.js:335:5)
at WritableState.onwrite (_stream_writable.js:105:5)
答案 0 :(得分:1)
您未在cb()
回调中调用appendFile()
。这需要表明您已完成data
,并且下一个块可以传递给_write()
。例如:
logStream.prototype._write = function logStream_write (data, enc, cb) {
fs.appendFile(this.file, data, 'utf-8', cb);
});