Download large file with node.js avoiding high memory consumption

后端 未结 6 943
梦毁少年i
梦毁少年i 2020-12-12 15:35

I`m trying to create a file downloader as a background service but when a large file is scheduled, it\'s first put in memory and then, at the end of the download the file is

6条回答
  •  醉话见心
    2020-12-12 15:54

    I changed the callback to:

    request.addListener('response', function (response) {
            var downloadfile = fs.createWriteStream(filename, {'flags': 'a'});
            sys.puts("File size " + filename + ": " + response.headers['content-length'] + " bytes.");
            response.addListener('data', function (chunk) {
                dlprogress += chunk.length;
                downloadfile.write(chunk, encoding='binary');
            });
            response.addListener("end", function() {
                downloadfile.end();
                sys.puts("Finished downloading " + filename);
            });
    
        });
    

    This worked perfectly.

提交回复
热议问题