首页 > 解决方案 > 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'但它什么也没做

标签: javascriptnode.jssynchronizationpipe

解决方案


end事件不会在请求上触发,而是在响应(docs)上触发:

 response.on("end", function() {
   console.log("done");
 });

推荐阅读