javascript - NodeJS 在继续下一次迭代之前用管道完成了文件的写入
问题描述
类似于这个问题,
我有一个通过 http.get 将文件下载到给定 url 的脚本。
在仅使用模块pipe
继续下一次迭代之前,如何确保完成?http/https
//nodejs default libs
var fs = require("fs");
var http = require('https');
function dlFile(fullFilePath, dlUrl, fsize, fname){
var file = fs.createWriteStream(fullFilePath); //fullFilePath will dictate where we will save the file + filename.
var rsult ='';
var downloadedFsize;
var stats; //stats of the file will be included here
var request = http.get( dlUrl, function(response) {
let rsult = response.statusCode;
//will respond with a 200 if the file is present
//404 if file is missing
response.pipe(file);
/*pipe writes the file...
how do we stop the iteration while it is not yet finished writing?
*/
console.log(" \n FILE : " + fname);
console.log("File analysis finished : statusCode: " + rsult + " || Saved on " + fullFilePath);
console.log(' \n Downloaded from :' + dlUrl);
console.log(' \n SQL File size is : ' + fsize);
//identify filesize
stats = fs.statSync(fullFilePath);
downloadedFsize = stats["size"]; //0 because the pipe isn't finished yet...
console.log(' actual file size is : ' + downloadedFsize);
}).on('error', function(e) {
console.error(e);
//log that an error happened to the file
}).on('end', function(e){
//tried putting the above script here but nothing happens
});
return rsult;
}
有没有类似于我上面想到的更清洁的方法?还是我应该以不同的方式处理这个问题?我试着把代码放在上面,.on('end'
但它什么也没做
解决方案
该end
事件不会在请求上触发,而是在响应(docs)上触发:
response.on("end", function() {
console.log("done");
});
推荐阅读
- mysql - 找到共同课程最多的学生和老师
- android - 如何修复预期的字符串,但在带有改造的嵌套数组上是 BEGIN_OBJECT
- sql - 为一组行生成 UniqueID 的最佳方法?
- r - 通过变量中的单独值在数据帧上应用长代码
- c# - 在 C# 中除以 2 个整数并获得一个双精度数
- javascript - JavaScript Azure Function stacktrace 中没有我的代码
- postgresql - 在 PostgreSQL 中存储任意精度整数
- html - Scroll in a deeply nested flex container - min-height not working
- vb.net - 修复错误目标主体名称不正确
- html - 背景图像在 chrome 中重复但不是 safari