【问题标题】:Detecting the end of a writeStream in Node检测 Node 中 writeStream 的结束
【发布时间】:2023-03-29 08:33:01
【问题描述】:

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

如何在 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');

【问题讨论】:

    标签: node.js file-io stream


    【解决方案1】:

    可写流有一个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 创建流处理器。

    【讨论】:

    猜你喜欢
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多