Node.js请求下载文件有时空或不存在 [英] Node.js request download file sometimes empty or no existing

查看:274
本文介绍了Node.js请求下载文件有时空或不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个带有node.js和请求模块的下载器。使用流语法我正在做

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆