18

これは私が持っているもので、順番に実行するとファイルがまだ存在しないため、エラーが発生し続けます。

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

1 に答える 1

29

書き込み可能なストリームには、データがフラッシュされたときに発行される終了イベントがあります。

以下を試してください。

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を使用して、ストリーム プロセッサを作成できます。

于 2013-11-07T06:45:00.693 に答える