Umar Syal Umar Syal - 3 months ago 9
Node.js Question

NodeJS: Fetching Data whenever the server starts

I'm new to Node and async programming. I'm building a website in which I have to fetch some data from external websites and show it to client(AngularJS Client).

What I want to do is that whenever my server starts, it should fetch data from the external websites and place it in DB.

I have following code in my server.js file:



var express = require('express'),
app = express(),
abc = require('./server/controllers/abc');

app.listen(3000, function () {
console.log('I\'m listening...');
});

app.on('listening', function(){
abc.visitPages;
});





and following snippet in abc.js:


module.exports.visitPages = function () {
console.log('Going to visitPages');
}





my server works fine but it does not go to the visitPages() function in abc.js any help in this regard would be very kind.

thanks in advance.

Answer

You need to make sure you're actually running the function. Unlike some other languages, you must provide the parentheses to signify that the function should be invoked in javascript.

Use abc.visitPages() inside your listen callback.

Also, I'm not sure app.on('listener') will ever fire. Looks like express doesn't support it. I would move the method call into your app.listen() callback instead.

app.listen(3000, function () {
  console.log('I\'m listening...');
  abc.visitPages();
});
Comments