繁体   English   中英

Node.js,Jsdom,HttpAgent的内存使用情况

[英]Memory usage with Node.js, Jsdom, HttpAgent

我制作了一个报废脚本,可以浏览博客以获取所有标题。 问题是Node在脚本运行时(数千个URL)继续使用越来越多的内存,直到8 go(max),然后脚本崩溃。

我的脚本使用循环,必须有一个简单的方法来清除内存?

这是一个代码示例:

var request = require('request'),
httpAgent = require('http-agent'),
jsdom = require('jsdom').jsdom,
myWindow = jsdom().createWindow(),
$ = require('jquery'),
jq = require('jquery').create(),
jQuery = require('jquery').create(myWindow),
profiler = require('v8-profiler');

profiler.startProfiling();

request({ uri:'http://www.guylabbe.ca' }, function (error, response, body) {
  if (error && response.statusCode !== 200) {
    console.log('Error when contacting URL')
  }


        var last_page_lk = $(body).find('.pane-content .pager li:last-child a').attr('href');
        var nb_pages = last_page_lk.substring(last_page_lk.indexOf('=')+1);
        var page_lk_base = last_page_lk.substring(0,last_page_lk.indexOf('='));

        var pages = Array();
        pages.push(page_lk_base);
        for(var i=1;i<=nb_pages;i++) {
            pages.push(page_lk_base+'='+i);
        }


        // parser les pages

        var fiches = Array();
        var agent2 = httpAgent.create('www.guylabbe.ca', pages);

        agent2.addListener('next', function (err, agent2) {

            var snapshot = profiler.takeSnapshot();


            $(body).find('.view span.field-content span.views-field-title').each(function(){
                fiches.push($(body).find(this).parents('a').attr('href'));
                //console.log($(body).find(this).html());
            });


            agent2.next();

        });
        agent2.start();

        agent2.addListener('stop', function (agent) {
          console.log('-------------------------------- (fini de cumuler les URL fiches) --------------------------------');

            // Parser les fiches

            var agent_fiches = httpAgent.create('www.guylabbe.ca', fiches);

            agent_fiches.addListener('next', function (err, agent_fiches) {

                console.log('log info');


                agent_fiches.next();

            });
            agent_fiches.start();

            agent_fiches.addListener('stop', function (agent) {
              console.log('-------------------------------- Eh voilà! --------------------------------');
            });

            agent_fiches.addListener('start', function (agent) {
              console.log('-------------------------------- C est parti... --------------------------------');
            });

        });



});

明确null null你不再需要它们的变种。 如果你在闭包之外创建变量,并在闭包内使用它,你应该在你不再需要它时将其置零。 看到这个线程并阅读接受的答案: 如何防止node.js中的内存泄漏?

我有一个类似的问题,jsdom泄漏内存。 在我的情况下,通过解决它来关闭jsdom窗口。 也许你应该在完成抓取之后添加myWindow.close() 请参阅相关答案https://stackoverflow.com/a/6891729/1824928

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM