简体   繁体   English

是否可以在Node中按需调用module.exports?

[英]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. 我有一个应用程序,在这里我可以调用API来获取标题并提取JSON并通过套接字将数据发送回客户端。 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. 我有我的index.js文件,在这里我仅调用从API抓取数据的函数,而newsDataFetcher.js是我使用请求模块向API请求数据的地方。 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. 对API的请求完成后,我将数据放入一个数组中,该数组位于newsDataFetcher.js文件的module.exports中,以及发出实际请求的函数。 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. 因此,由于该数组位于module.exports ,因此当我在index.js文件中需要newsDataFetcher.js文件时,将传递一个空数组。 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? 因此,这使我想到了一个问题:是否仍然可以按需调用module.exports ,以便它不会传递空数组,而仅在从API下载完数据后才传递该数组?

index.js : 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: newsDataFetcher.js文件:

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
}

You can do some like this: 您可以这样做:

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

// index.js
io.sockets.emit('news', newsDataFetcher.news());

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM