Dan*_*res 6 javascript asynchronous download request node.js
我正在用node.js和请求模块编写一个下载程序.使用我正在做的流语法
var r = request(url).pipe(fs.createWriteStream(targetPath));
r.on('error', function(err) { console.log(err); });
r.on('finish', cb);
Run Code Online (Sandbox Code Playgroud)
下载文件,保存并调用回调.但是,在近50%的情况下,文件为空或根本不创建.没有error发生任何事件.finish即使文件尚未(完全)写入,似乎触发了事件.
上下文:整个事情都包含在async.each调用中.
有线索吗?谢谢!
小智 12
您需要在访问文件之前关闭该文件:
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) });
Run Code Online (Sandbox Code Playgroud)
顺便提一下,如果网址回复任何http错误(例如404未找到),那么不会触发'错误'事件,因此您应该单独检查:
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);
Run Code Online (Sandbox Code Playgroud)