How to download a file with Node.js (without using third-party libraries)?

后端 未结 28 1201
逝去的感伤
逝去的感伤 2020-11-22 03:37

How do I download a file with Node.js without using third-party libraries?

I don\'t need anything special. I only want to download a file from a giv

相关标签:
28条回答
  • 2020-11-22 03:55

    Hi,I think you can use child_process module and curl command.

    const cp = require('child_process');
    
    let download = async function(uri, filename){
        let command = `curl -o ${filename}  '${uri}'`;
        let result = cp.execSync(command);
    };
    
    
    async function test() {
        await download('http://zhangwenning.top/20181221001417.png', './20181221001417.png')
    }
    
    test()
    

    In addition,when you want download large、multiple files,you can use cluster module to use more cpu cores.

    0 讨论(0)
  • 2020-11-22 03:57

    As Michelle Tilley said, but with the appropriate control flow:

    var http = require('http');
    var fs = require('fs');
    
    var download = function(url, dest, cb) {
      var file = fs.createWriteStream(dest);
      http.get(url, function(response) {
        response.pipe(file);
        file.on('finish', function() {
          file.close(cb);
        });
      });
    }
    

    Without waiting for the finish event, naive scripts may end up with an incomplete file.

    Edit: Thanks to @Augusto Roman for pointing out that cb should be passed to file.close, not called explicitly.

    0 讨论(0)
  • 2020-11-22 03:57

    I suggest you to use res.download same as follow:

    app.get('/download', function(req, res){
      const file = `${__dirname}/folder/abc.csv`;
      res.download(file); // Set disposition and send it.
    });
    
    0 讨论(0)
  • 2020-11-22 03:59
    function download(url, dest, cb) {
    
      var request = http.get(url, function (response) {
    
        const settings = {
          flags: 'w',
          encoding: 'utf8',
          fd: null,
          mode: 0o666,
          autoClose: true
        };
    
        // response.pipe(fs.createWriteStream(dest, settings));
        var file = fs.createWriteStream(dest, settings);
        response.pipe(file);
    
        file.on('finish', function () {
          let okMsg = {
            text: `File downloaded successfully`
          }
          cb(okMsg);
          file.end(); 
        });
      }).on('error', function (err) { // Handle errors
        fs.unlink(dest); // Delete the file async. (But we don't check the result)
        let errorMsg = {
          text: `Error in file downloadin: ${err.message}`
        }
        if (cb) cb(errorMsg);
      });
    };
    
    0 讨论(0)
  • 2020-11-22 04:03

    Solution with timeout, prevent memory leak :

    The following code is based on Brandon Tilley's answer :

    var http = require('http'),
        fs = require('fs');
    
    var request = http.get("http://example12345.com/yourfile.html", function(response) {
        if (response.statusCode === 200) {
            var file = fs.createWriteStream("copy.html");
            response.pipe(file);
        }
        // Add timeout.
        request.setTimeout(12000, function () {
            request.abort();
        });
    });
    

    Don't make file when you get an error, and prefere to use timeout to close your request after X secondes.

    0 讨论(0)
  • 2020-11-22 04:03
    const download = (url, path) => new Promise((resolve, reject) => {
    http.get(url, response => {
        const statusCode = response.statusCode;
    
        if (statusCode !== 200) {
            return reject('Download error!');
        }
    
        const writeStream = fs.createWriteStream(path);
        response.pipe(writeStream);
    
        writeStream.on('error', () => reject('Error writing to file!'));
        writeStream.on('finish', () => writeStream.close(resolve));
    });}).catch(err => console.error(err));
    
    0 讨论(0)
提交回复
热议问题