在Node中检测writeStream的结尾 [英] Detecting the end of a writeStream in Node
本文介绍了在Node中检测writeStream的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我所拥有的,并且我不断收到错误消息,因为当我按顺序执行该文件时,该文件尚不存在.
This is what I've got, and I keep getting an error because the file doesn't exist yet when I just do it sequentially.
如何在writeStream关闭时触发动作?
How can I trigger an action upon the writeStream getting closed?
var fs = require('fs'), http = require('http');
http.createServer(function(req){
req.pipe(fs.createWriteStream('file'));
/* i need to read the file back, like this or something:
var fcontents = fs.readFileSync(file);
doSomethinWith(fcontents);
... the problem is that the file hasn't been created yet.
*/
}).listen(1337, '127.0.0.1');
推荐答案
可写流具有 finish 刷新数据时发出的事件.
Writable streams have a finish event that is emitted when the data is flushed.
尝试以下操作;
var fs = require('fs'), http = require('http');
http.createServer(function(req, res){
var f = fs.createWriteStream('file');
f.on('finish', function() {
// do stuff
res.writeHead(200);
res.end('done');
});
req.pipe(f);
}).listen(1337, '127.0.0.1');
尽管我不会重新读取文件.您可以使用通过来创建流处理器.
Though I wouldnt re-read the file. You can use through to create a stream processor.
这篇关于在Node中检测writeStream的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文