The request makes the process out of memory when loading large media files

I wrote a simple script to download video files from a CDN, where direct URLs are easy to create, like http://something.com/N.mp4 , where N is a number.

The problem is that when downloading files larger than ~ 300 MB, the files are displayed perfectly on the hard drive, but before the callback request(...), the memory allocation fails:

FATAL ERROR: CALL_AND_RETRY_0 Allocation failed - process out of memory

Is this due to some serious bad practice? Can I requestupload media files of this size?

Environment: Win7, 4 GB + free RAM, Node v0.10.31

var request = require('request');
var async = require('async');
var fs = require('fs');
var start = +process.argv[2] || 1;
var end = +process.argv[3] || 50;
var url = 'http://something.com/';

try {
  fs.mkdirSync(__dirname + '/videos/');
} catch (e) {}

var index = start;

async.whilst(
  function () { return index <= end; },
  function (callback) {
    var fileName = index + '.mp4';
    console.log('Started: ' + fileName);
    console.time('Done (' + fileName + ')');
    request(url + fileName, function() {
      console.timeEnd('Done (' + fileName + ')');
      index++;
      callback(null);
    }).pipe(fs.createWriteStream(__dirname + '/videos/' + fileName));
  },
  function (err) {
    if (err) {
      return console.error(err);
    }
    console.log('Script finished.');
  }
);

Example console output:

> node index.js 3
Started: 3.mp4
Done (3.mp4): 296592ms
Started: 4.mp4
Done (4.mp4): 369718ms
Started: 5.mp4
FATAL ERROR: CALL_AND_RETRY_0 Allocation failed - process out of memory
+4
source share
2 answers

request , . finish fs.

var writer = fs.createWriteStream(__dirname + '/videos/' + fileName);
writer.on('finish', function() {
  // ...
  index++;
  callback(null);
});
request(url + fileName).pipe(writer);
+4

, 3 50, , . , . async.waterfall :

var tasks = [];

for (; index < end; index++) {
    tasks.push(function(callback) {
        var fileName = index + '.mp4';
        console.log('Started: ' + fileName);
        console.time('Done (' + fileName + ')');
        request(url + fileName, function() {
            console.timeEnd('Done (' + fileName + ')');
            callback(null);
        }).pipe(fs.createWriteStream(__dirname + '/videos/' + fileName));
    });
}

async.waterfall(tasks, function(err) {
    if (err) {
        return console.error(err);
    }
    console.log('Script finished.');
});
-2

Source: https://habr.com/ru/post/1584766/


All Articles