【问题标题】:Node.js - loop through JSON list of files to save locally using http.getNode.js - 遍历 JSON 文件列表以使用 http.get 在本地保存
【发布时间】:2016-10-18 10:23:06
【问题描述】:

我有一个 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);
                });
            });
        });

【问题讨论】:

  • 您似乎遇到了异步竞争问题。也许尝试将“var newfile = ...”放在“http.get ...”的回调中。然后将“response.pipe...”移动到“newfile.on('finish')”的回调中
  • filelink, newfile, fn & cb 闭包包装http.get 调用,因为参数可能有效
  • 谢谢@josephnvu,尝试了你的建议,但所有文件都是空的,而不仅仅是几个。
  • 对不起@Jaganathan Bantheswaran 我不确定你的意思。

标签: javascript json node.js http


【解决方案1】:

由于您的下载代码在 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)
});

【讨论】:

  • 感谢您的帮助。不幸的是,我仍然得到一些空文件:(
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多