【问题标题】:How to download image folder from website to local directory using nodejs如何使用nodejs将图像文件夹从网站下载到本地目录
【发布时间】:2015-09-11 00:38:08
【问题描述】:

我想下载包含图片数量的图片文件夹。 我需要下载到我的本地目录。 我下载了一张给出图像名称的图像。 但我无法理解如何为多个图像本身做到这一点。 这是我的代码。

var http = require('http');
var fs = require('fs');

var file = fs.createWriteStream("./downloads");
var request = http.get("http://www.salonsce.com/extranet/uploadfiles" + image.png, function(response) {
  response.pipe(file);
});

提前致谢。

【问题讨论】:

    标签: javascript html express


    【解决方案1】:

    要在 Node.js 中使用 curl 下载文件,您需要使用 Node 的 child_process 模块。您必须使用 child_process 的 spawn 方法调用 curl。为此,为了方便起见,我使用 spawn 而不是 exec - spawn 返回一个带有数据事件的流,并且没有与 exec 不同的缓冲区大小问题。这并不意味着 exec 不如 spawn;事实上,我们将使用 exec 来使用 wget 下载文件。

    // Function to download file using curl
    var download_file_curl = function(file_url) {
    
        // extract the file name
        var file_name = url.parse(file_url).pathname.split('/').pop();
        // create an instance of writable stream
        var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);
        // execute curl using child_process' spawn function
        var curl = spawn('curl', [file_url]);
        // add a 'data' event listener for the spawn instance
        curl.stdout.on('data', function(data) { file.write(data); });
        // add an 'end' event listener to close the writeable stream
        curl.stdout.on('end', function(data) {
            file.end();
            console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
        });
        // when the spawn child process exits, check if there were any errors and close the writeable stream
        curl.on('exit', function(code) {
            if (code != 0) {
                console.log('Failed: ' + code);
            }
        });
    };
    

    【讨论】:

      【解决方案2】:

      更好的方法是并行使用另一个名为glob 的工具。喜欢,

      首先安装它

      npm install glob

      然后,

      var glob = require("glob");
      var http = require('http');
      var fs = require('fs');
      
      var file = fs.createWriteStream("./downloads");
      
      // options is optional
      //options = {};
      glob('http://www.salonsce.com/extranet/uploadfiles/*', options, function (er, files) {
        //you will get list of files in the directory as an array.
        // now use your previus logic to fetch individual file
        // the name of which can be found by iterating over files array
        // loop over the files array. please implement you looping construct.
        var request = http.get(files[i], function(response) {
            response.pipe(file);
        });
      
      });
      

      【讨论】:

      • 完美的 sn-p 语法。我将所有图片下载到本地文件夹中。
      猜你喜欢
      • 1970-01-01
      • 2019-03-29
      • 2011-01-23
      • 2020-08-15
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      相关资源
      最近更新 更多