Node.js -使用http.get循环遍历要保存在本地的JSON文件列表

Node.js - loop through JSON list of files to save locally using http.get

本文关键字:存在 JSON 列表 文件 保存 使用 js http get 遍历 循环      更新时间:2023-09-26

我有一个JSON文件,其中包含服务器上的文件名列表。我需要遍历这个列表并在本地保存每个文件。我在一定程度上做到了这一点。有时它像魔法一样有效,有时则不然,最后我的文件是空的。

我知道这可能是开始下载下一个文件之前,以前已经完成,但我正在努力重写这个,以便我得到一个回调时,文件完成,开始下载下一个。我不是经验丰富的客户端编码,所以会很感激一些帮助与此。

var filefolder = 'http://www.example.com/files/';
        var newdir = nw.App.dataPath;
        $.each(jsonFiles, function(i, fn) {
            //read and download to save locally
            var filelink = filefolder + '/' + fn;
            var newfile = fs.createWriteStream(newdir+'/files/' + '/' + fn);
            var request = http.get(filelink, function(response) {
                response.pipe(newfile );
                console.log(fn);
                newfile.on('finish', function() {
                    newfile.close(cb);
                });
            });
        });

因为你的下载代码在each循环内,而http.get是异步的,你必须用闭包来包装调用。

像这样,

var filefolder = 'http://www.example.com/files/';
var newdir = nw.App.dataPath;
$.each(jsonFiles, function(i, fn) {
    //read and download to save locally
    var filelink = filefolder + '/' + fn;
    var newfile = fs.createWriteStream(newdir + '/files/' + '/' + fn);
   (function(filelink, newfile, fn, cb) {
       var request = http.get(filelink, function(response) {
                 response.pipe(newfile);
                 console.log(fn);
                 newfile.on('finish', function() {
                     newfile.close(cb);
                 });
             });
   })(filelink, newfile, fn, cb)
});