Javascript Nodejs:将文件写入hd后访问该文件会产生错误。为什么?
我正在下载一些图像,希望在X被写入后直接访问这些文件。我等待结束事件,然后尝试访问文件。 有时这会失败,因为文件似乎没有被写入Javascript Nodejs:将文件写入hd后访问该文件会产生错误。为什么?,javascript,node.js,fs,Javascript,Node.js,Fs,我正在下载一些图像,希望在X被写入后直接访问这些文件。我等待结束事件,然后尝试访问文件。 有时这会失败,因为文件似乎没有被写入 image_file.end([chunk], [encoding], [callback]) 如果我对文件的访问进行了评论,图像将按预期下载并保存 我的文件下载后如何访问?我需要等待其他活动吗? // id changes dynamically in loop var tmp_file = os.tmpdir() + "/" + id + "_image_file
image_file.end([chunk], [encoding], [callback])
如果我对文件的访问进行了评论,图像将按预期下载并保存
我的文件下载后如何访问?我需要等待其他活动吗?
// 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
});
});
image_file.end()不是原子的,您需要等待回调以确保它已被写入
image_file.end([chunk], [encoding], [callback])
或者,你也可以在writeStream上观察结尾
image_file.on('finish', callback)
+1我尝试了“response.on('finish'),”但是“image_file.on('finish'),“完成工作-感谢Shappy帮助!”,
response.on('finish')…
标记了来自读流的内容的结束,您需要知道写流何时完成。