Node.js请求下载文件有时空或不存在 [英] Node.js request download file sometimes empty or no existing
问题描述
var r = request(url).pipe(fs.createWriteStream(targetPath));
r.on('error',function(err){console.log(err);});
r.on('finish',cb);
下载文件,保存并调用回调。然而,在几乎50%的情况下,文件是空的或根本没有创建。不发送错误
事件。即使没有(完全)写入文件,似乎也触发完成
事件。
上下文:整个事情都被包裹到 async.each
呼叫中。
任何线索?谢谢!
您需要关闭文件才能访问它:
var file = fs.createWriteStream(targetPath);
var r = request(url).pipe(file);
r.on('error',function(err){console.log(err);});
r.on('finish',function(){file.close(cb)});
顺便提一句,如果url回复任何http错误(如404未找到),那么不要触发'错误'事件,所以你应该分开检查:
function handleFailure(err){console.log (呃); };
var file = fs.createWriteStream(targetPath);
请求(url,function(error,response){
if(response.statusCode!= 200){
console.log(oops,got a+ response.statusCode);
return
}
// close is async,你必须等到关闭完成否则
//你会(很少)不能访问文件回调
file.on('finish',function(){file.close(cb)});
response.pipe(file).on('error',handleFailure)
file.on('error',handleFailure)
})。on('error',handleFailure);
I'm writing a downloader with node.js and the request module. Using the stream syntax I'm doing
var r = request(url).pipe(fs.createWriteStream(targetPath));
r.on('error', function(err) { console.log(err); });
r.on('finish', cb);
to download the file, save it and call the callback. However, in almost 50% of the cases the file is either empty or not created at all. No error
event is emitted. It seems like the finish
event is triggered even though the file wasn't (completely) written yet.
Context: The whole thing is wrapped into async.each
calls.
Any clues? Thanks!
You need to close the file before accessing it:
var file = fs.createWriteStream(targetPath);
var r = request(url).pipe(file);
r.on('error', function(err) { console.log(err); });
r.on('finish', function() { file.close(cb) });
Incidentally, if the url replies with any http error (such as a 404 not found), that won't trigger the 'error' event, so you should probably check that separately:
function handleFailure(err) { console.log(err); };
var file = fs.createWriteStream(targetPath);
request(url, function(error, response) {
if (response.statusCode != 200) {
console.log("oops, got a " + response.statusCode);
return
}
// close is async, and you have to wait until close completes otherwise
// you'll (very rarely) not be able to access the file in the callback.
file.on('finish', function() { file.close(cb) });
response.pipe(file).on('error', handleFailure)
file.on('error', handleFailure)
}).on('error', handleFailure);
这篇关于Node.js请求下载文件有时空或不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!