2015-06-25 24 views
0

我有一個Web應用程序。在每個請求中,它會將整個文件加載到內存中,並與內容進行異步操作。限制工作量以控制內存使用量

爲了避免內存不足,我想限制可以同時處理的文件數量。如果文件的大小是恆定的並且預先知道,則async.queue將是完美的。但我不知道文件大小。所以,更準確地說,我真的想限制我當前佔用的內存量,而不是指定文件數量的固定限制。

我的問題是,是否有一個圖書館,在那裏,將讓我做這樣的事情:需要對這個

// Use the fictitious Limiter 
var limiter = new Limiter(worker, 10 * 1024 * 1024); // limit to 10 MB 

// process foo.txt, which we know is 6MB 
limiter.push("foo.txt", 6 * 1024 * 1024); 
// ask to process bar.txt, but it will be delayed until foo is complete 
// because 6 + 6 > 10 
limiter.push("bar.txt", 6 * 1024 * 1024); 

// The worker is the same as the one used by async.queue 
function worker(task, callback){ 
    var filename = task; 
    //load whole file and do asynchronous stuff with it 
    doSomething(filename, function(){ 
     // we're done with the file 
     callback(); 
    }); 
} 
+0

對不起......題外話,因爲:「請給軟件庫」。 –

+1

不,但是很容易構建你自己的,看起來你在你的例子中有一半的代碼... – dandavis

+1

你真的在尋找一個修改過的信號量...選擇一個現有的信號量實現並根據你的需要進行調整(不要忘記回饋!) – Amit

回答

0

沒有什麼比一個信號量多。見https://github.com/abrkn/semaphore.js

的代碼處理文件在內存中,然後將遵循這種模式:

var sem = require('semaphore')(10 * 1024 * 1024); 

var size = 6 * 1024 * 1024; 
processFile("foo.txt", size); 
processFile("bar.txt", size); 


function processFile(filename, size){ 
    sem.take(size, function(){ 
     console.log(filename); 
     // Pretend it takes 1 second to deal with file 
     setTimeout(function(){ 
      sem.leave(size); 
     }, 1000); 
    }); 
}