检测Node中writeStream的结束

时间:2013-11-07 06:28:53

标签: node.js file-io stream

这就是我所拥有的,并且我一直收到错误,因为当我按顺序执行时,该文件还不存在。

如何在writeStream关闭时触发操作?

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');

1 个答案:

答案 0 :(得分:25)

可写流有一个finish事件,该事件在刷新数据时发出。

尝试以下方法;

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');

虽然我不会重新阅读该文件。您可以使用through创建流处理器。