使用Request模块下载文件,pipe方法写入文件流,后续对文件计算hash值,出现hash值出错的问题,代码如下:
request
.get(aliyunFilePath, {
headers: {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36'}
})
.on('error', function (err) {
cont(tools.apiErr(err));
})
.on('response', function (response) {
response.on('end', function () {
if (response.statusCode === 200) {
filePath = localFilePath;
cont(null);
return;
}
cont(tools.apiErr('文件下载失败:' + response.statusCode));
});
})
.pipe(fs.createWriteStream(localFilePath));
。。。
var fileMD5 = security.fileMD5(filePath);
查询分析发现,文件写入流有个finish事件,而不应该使用response的end事件,参考:https://github.com/request/request/issues/1645,修正后的代码如下:
request
.get(aliyunFilePath, {
headers: {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36'}
})
.on('error', function (err) {
cont(tools.apiErr(err));
})
.on('response', function (response) {
response.on('end', function () {
if (response.statusCode !== 200) {
cont(tools.apiErr('文件下载失败:' + response.statusCode));
}
});
})
.pipe(fs.createWriteStream(localFilePath))
.on('finish', function () {
filePath = localFilePath;
cont(null);
});
。。。
var fileMD5 = security.fileMD5(filePath);
写在这里,以作记录。