Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
Is it possible to call module.exports on demand in Node?

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
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can do some like this:

// newsDataFetcher.js
module.exports = {
    getNewsData: getNewsData,
    news: function() {
        return news;
    }
}

// index.js
io.sockets.emit('news', newsDataFetcher.news());
over 4 years ago · Santiago Trujillo Relatório

0

You can use singleton pattern to achieve this.

class NewsDataFetcher {
    constructor() {
        this.news = [];
    }

    getNewsData() {
         const self = this;
         request({
             url: nyTimesApi,
             json: true
         }, function (err, res, body) {
             self.news = body.results;
         });
    }
}
module.exports = new NewsDataFetcher();

In the main page.

var newsDataFetcher = require('./newsDataFetcher');
newsDataFetcher.getNewsData(); // to fetch new data;
// To get news data
console.log(newsDataFetcher.news); // will always refer to one instance of news since you are using singleton.
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda