Download large file with node.js avoiding high memory consumption

后端 未结 6 947
梦毁少年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:56

    When downloading large file please use fs.write and not writeFile as it will override the previous content.

    function downloadfile(res) {
        var requestserver = http.request(options, function(r) {
            console.log('STATUS: ' + r.statusCode);
            console.log('HEADERS: ' + JSON.stringify(r.headers));
    
            var fd = fs.openSync('sai.tar.gz', 'w');
    
            r.on('data', function (chunk) {
                size += chunk.length;
                console.log(size+'bytes received');
                sendstatus(res,size);
                fs.write(fd, chunk, 0, chunk.length, null, function(er, written) {
                });
            });
            r.on('end',function(){
                console.log('\nended from server');
                fs.closeSync(fd);
                sendendstatus(res);
            });
        });
    }
    

提交回复
热议问题