【问题标题】:Nodejs: Accessing file after writing it to the hd yields error. Why?Nodejs:将文件写入高清后访问文件会产生错误。为什么?
【发布时间】:2014-05-08 23:35:49
【问题描述】:

我正在下载几张图片,并希望在它们被写入后直接访问这些文件。我等待结束事件,然后尝试访问文件。 有时这会失败,因为似乎没有写入文件。

如果我对文件的访问进行评论,则图像将全部下载并按预期保存。

我如何在下载文件后访问我的文件?我需要等待另一个事件吗?

// id changes dynamically in loop
var tmp_file = os.tmpdir() + "/" + id + "_image_file.jpg";
http.get(image_url, function(response) {
    var image_file = fs.createWriteStream(tmp_file); 
    response.on('data', function(chunk) {
        image_file.write(chunk);
    }).on('end', function() {
    image_file.end();
        console.log("File written: " + image_file.path);

        // check filesize - it happens that the filesize is 0 by now
    var stats = fs.statSync(tmp_file);
    var fileSizeInBytes = stats["size"];

        // use imagemagick to process file which sometimes isn't written by now
        im.readMetadata(tmp_file, function(err, metadata){
        if (err) throw err; // throws error
    });
});

【问题讨论】:

    标签: javascript node.js fs


    【解决方案1】:

    image_file.end() 不是原子的,你需要等待回调确定它已经被写入。

    image_file.end([chunk], [encoding], [callback])
    

    或者您可以在 writeStream 上观看完成

    image_file.on('finish', callback)
    

    【讨论】:

    • +1 我已经尝试过 "response.on('finish'," - 但是 "image_file.on('finish'," 可以完成工作 - 谢谢
    • 很高兴为您提供帮助!respose.on('finish'... 标志着来自您的读取流的内容结束,您需要知道您的写入流何时完成。
    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2023-03-27
    • 2021-07-23
    • 2015-08-12
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多