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

后端 未结 28 1253
逝去的感伤
逝去的感伤 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: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.

提交回复
热议问题