首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用nodejs将图片文件夹从网站下载到本地目录

如何使用nodejs将图片文件夹从网站下载到本地目录
EN

Stack Overflow用户
提问于 2015-09-07 18:54:30
回答 2查看 1.3K关注 0票数 0

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

代码语言:javascript
复制
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);
});

提前谢谢。

EN

回答 2

Stack Overflow用户

发布于 2015-09-07 19:32:29

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

代码语言:javascript
复制
// 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);
        }
    });
};
票数 1
EN

Stack Overflow用户

发布于 2015-09-07 19:33:20

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

首先用以下命令安装它

npm install glob

然后,

代码语言:javascript
复制
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);
  });

});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32436935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档