I have an app where I call an API to get headlines and digest that JSON and send the data back to the client via sockets. I have modularized all my code and used different files to stay organized. I have my index.js file, where I merely call the functions to grab to data from the API and newsDataFetcher.js is where I make the request to the API for the data using the request module. My issue is that since the request I am making is asynchronous, the data doesn't get passed to the main server file and therefore the socket doesn't send any data. After the request to the API finishes, I put the data into an array and that array is in the module.exports of my newsDataFetcher.js file, along with the function that makes the actual request. So since the array is in the module.exports, an empty array is passed when I require the newsDataFetcher.js file in the index.js file. So, that brings me to the question: is there anyway to call module.exports "on demand" so that it doesn't pass an empty array and it only passes the array when the data is finished downloading from the API?
index.js :
var newsDataFetcher = require('./newsDataFetcher');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var news = []; //array for news headlines and abstracts
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/views/routes/'));
server.listen(8888);
console.log("Running server on http://localhost:8888 ....");
newsDataFetcher.getNewsData();
news = newsDataFetcher.news;
setInterval(function () {
newsDataFetcher.getNewsData();
news = newsDataFetcher.news;
}, 6000000);
setInterval(function () {
sendAllData()
}, 1000);
function sendAllData() {
io.sockets.emit('news', news);
}
newsDataFetcher.js file:
var request = require('request');
var nyTimesApi = "http://api.nytimes.com/svc/topstories/v1/home.json?api-key=" + nyTimesApiKey_DEV;
var news = []; //array for news headlines and abstracts
function getNewsData() {
request({
url: nyTimesApi,
json: true
}, function (err, res, body) {
news = body.results;
});
}
module.exports = {
getNewsData: getNewsData,
news: news
}
via rakeshdas
No comments:
Post a Comment