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

后端 未结 28 1282
逝去的感伤
逝去的感伤 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 04:14

    Download using promise, which resolve a readable stream. put extra logic to handle the redirect.

    var http = require('http');
    var promise = require('bluebird');
    var url = require('url');
    var fs = require('fs');
    var assert = require('assert');
    
    function download(option) {
        assert(option);
        if (typeof option == 'string') {
            option = url.parse(option);
        }
    
        return new promise(function(resolve, reject) {
            var req = http.request(option, function(res) {
                if (res.statusCode == 200) {
                    resolve(res);
                } else {
                    if (res.statusCode === 301 && res.headers.location) {
                        resolve(download(res.headers.location));
                    } else {
                        reject(res.statusCode);
                    }
                }
            })
            .on('error', function(e) {
                reject(e);
            })
            .end();
        });
    }
    
    download('http://localhost:8080/redirect')
    .then(function(stream) {
        try {
    
            var writeStream = fs.createWriteStream('holyhigh.jpg');
            stream.pipe(writeStream);
    
        } catch(e) {
            console.error(e);
        }
    });
    

提交回复
热议问题