I have a node.js script that continuously requests a page, sort of like a cron job.
However, after a few minutes Node starts to use a lot of CPU (up to 70%) and memory (up to 200mb).
What is wrong with my script?
function cron(path)
{
var http = require('http');
var site = http.createClient(443, 'www.website.com', true);
var request = site.request('GET', path, {'host': 'www.website.com'});
request.end();
request.on('response', function (response) {
setTimeout(function(){cron(path)},15000);
});
}
cron('/path/to/page');
For every response you create a new
cronjob. Log your responses. If your getting more then 1 from your request then your exponantially creating more cron jobs.Your creating a
function() {}with a reference topath. So the entire scope state is kept. you want to free memory by adding this:Your calling
require("http")inside a function rather then outside in module scope. You only need to gethttponce so place at the top of your file in module scope.