Node.js刮板中的内存泄漏 [英] Memory leak in Node.js scraper

查看:63
本文介绍了Node.js刮板中的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个使用Node.js用JavaScript编写的简单抓取工具,用于抓取Wikipedia以获取元素周期表元素数据.依赖项是 jsdom 用于DOM操作,而

This is a simple scraper written in JavaScript with Node.js, for scraping Wikipedia for periodic table element data. The dependencies are jsdom for DOM manipulation and chain-gang for queuing.

在大多数情况下,它都能正常工作(它不能很好地处理错误),并且代码也不是太糟糕,我敢说要尝试一下,但是它有一个严重的错误-它会泄漏内存可怕的是,每个元素占计算机内存的0.3%到0.6%之间的任何地方,因此,当它领先时,它将占用接近20%的空间,这显然是不可接受的.

It works fine, most of the time (it doesn't handle errors gracefully), and the code isn't too bad, dare I say for a for attempt, but there is a serious fault with it - it leaks memory horribly, anywhere from 0.3% to 0.6% of the computer's memory for each element, such that by the time it gets to lead it would be using somewhere close to 20%, which is plainly unacceptable.

我曾尝试与探查器一起使用,但是我发现它们没有帮助或难以解释数据.我怀疑这与processElement的传递方式有关,但是我很难将队列代码重写为更优雅的内容.

I've tried working with profilers, but I have either not found them to be helpful or have difficulty interpreting the data. I suspect it has something to do with the way processElement gets passed around, but I have difficulty in rewriting the queue code into something more elegant.

var fs = require('fs'),
    path = require('path'),
    jsdom = require("jsdom"),
    parseUrl = require('url').parse,
    chainGang = require('chain-gang');

var chain = chainGang.create({
    workers: 1
});

var Settings = {
    periodicUrl: 'http://en.wikipedia.org/wiki/Template:Periodic_table',
    periodicSelector: '#bodyContent > table:first',
    pathPrefix: 'data/',
    ignoredProperties: ['Pronunciation']
};

function writeToFile(output) {
    var keys = 0;

    // Huge nests for finding the name of the element... yeah
    for(var i in output) {
        if(typeof output[i] === 'object' && output[i] !== null){
            for(var l in output[i]) {
                if(l.toLowerCase() === 'name') {
                    var name = output[i][l];
                }
            }

            keys += Object.keys(output[i]).length;
        }
    }

    console.log('Scraped ' + keys + ' properties for ' + name);
    console.log('Writing to ' + Settings.pathPrefix + name + '.json');
    fs.writeFile(Settings.pathPrefix + name + '.json', JSON.stringify(output));
}

// Generic create task function to create a task function that
// would be passed to the chain gang
function createTask (url, callback) {
    console.log('Task added - ' + url);

    return function(worker){
        console.log('Requesting: ' +url);

        jsdom.env(url, [
            'jquery.min.js' // Local copy of jQuery
        ], function(errors, window) {
            if(errors){
                console.log('Error! ' + errors)
                createTask(url, callback);
            } else {
                // Give me thy $
                var $ = window.$;

                // Cleanup - remove unneeded elements
                $.fn.cleanup = function() {
                    return this.each(function(){
                        $(this).find('sup.reference, .IPA').remove().end()
                            .find('a, b, i, small, span').replaceWith(function(){
                                return this.innerHTML;
                            }).end()
                            .find('br').replaceWith(' ');
                    });
                }

                callback($);
            }

            worker.finish();
        });
    }
}

function processElement ($){
    var infoBox = $('.infobox'),
        image = infoBox.find('tr:contains("Appearance") + tr img:first'),
        description = $('#toc').prevAll('p').cleanup(),
        headers = infoBox.find('tr:contains("properties")'),
        output = {
            Appearance: image.attr('src'),
            Description: $('.infobox + p').cleanup().html()
        };

    headers.each(function(){
        var that = this,
            title = this.textContent.trim(),
            rowspan = 0,
            rowspanHeading = '';

        output[title] = {};

        $(this).nextUntil('tr:has(th:only-child)').each(function(){
            var t = $(this).cleanup(),
                headingEle = t.children('th'),
                data = t.children('td').html().trim();

            if(headingEle.length) {
                var heading = headingEle.html().trim();
            }

            // Skip to next heading if current property is ignored
            if(~Settings.ignoredProperties.indexOf(heading)) {
                return true;
            }

            if (rowspan) {
                output[title][rowspanHeading][data.split(':')[0].trim()] = data.split(':')[1].trim();
                rowspan--;
            } else if (headingEle.attr('rowspan')){
                rowspan = headingEle.attr('rowspan') - 1;
                rowspanHeading = heading;

                output[title][heading] = {};
                output[title][heading][data.split(':')[0]] = data.split(':')[1];
            } else if (~heading.indexOf(',')){
                data = data.split(',');

                heading.split(',').forEach(function(v, i){
                    output[title][v.trim()] = data[i].trim();
                });
            } else {
                output[title][heading] = data;
            }
        });
    });

    writeToFile(output);
}

function fetchElements(elements) {
    elements.forEach(function(value){
        // Element URL used here as task id (second argument)
        chain.add(createTask(value, processElement), value);
    });
}

function processTable($){
    var elementArray = $(Settings.periodicSelector).find('td').map(function(){
        var t = $(this),
            atomicN = parseInt(t.text(), 10);

        if(atomicN && t.children('a').length) {
            var elementUrl = 'http://' + parseUrl(Settings.periodicUrl).host + t.children('a:first').attr('href');

            console.log(atomicN, t.children('a:first').attr('href').split('/').pop(), elementUrl);
            return elementUrl;
        }
    }).get();

    fetchElements(elementArray);
    fs.writeFile(Settings.pathPrefix + 'elements.json', JSON.stringify(elementArray));
}

// Get table - init
function getPeriodicList(){
    var elementsList = Settings.pathPrefix + 'elements.json';

    if(path.existsSync(elementsList)){
        var fileData = JSON.parse(fs.readFileSync(elementsList, 'utf8'));
        fetchElements(fileData);
    } else {
        chain.add(createTask(Settings.periodicUrl, processTable));
    }
}

getPeriodicList();

推荐答案

对于带有节点的类似jQuery的html处理,我现在使用 cheerio 而不是jsdom.到目前为止,在几个小时内抓取和解析超过1万个页面时,我还没有看到任何内存泄漏.

For jQuery-like html processing with node i use now cheerio instead of jsdom. So far, i have not seen any memory leaks while scrapping and parsing over 10K pages for a couple of hours.

这篇关于Node.js刮板中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆