【问题标题】:Is there a way to do module.exports a variable within a http request有没有办法在 http 请求中执行 module.exports 变量
【发布时间】:2018-07-06 15:06:32
【问题描述】:

好的,所以我已经在互联网上搜索了这个问题的答案,但都失败了。所以我的问题是保存和存储来自 https GET 请求的信息并在其他地方使用它。是的,我知道这是处理异步性质的 Node JS。我的想法是使用 module.exports.json_data 并要求在同一文件夹中的新文件中并访问该文件。

const https = require("https");
var json;
function getting_order(){

    var options = {
        hostname: "some_url.com",
        port: 443,
        path: "/certain/endpoint/",
        method: "GET"
    };


    var req = https.request(options, (res) => {
        let responseBody = "";

        res.setEncoding("UTF-8");

        res.on('data',(chunk) => {
            responseBody += chunk;
        })

        res.on('end',() =>{
            json = JSON.parse(responseBody)
            exports.json = json;
        })

    });
    req.end();
};

module.exports.getting_order = getting_order;

注意exports.json = json in:

res.on('end',() =>{
   json = JSON.parse(responseBody)
   exports.json = json;
})

所以我的问题是,这是否有效并且实际上保存了该 json 以在另一个文件的其他地方使用?

【问题讨论】:

  • 是的,你可以这样做。但是当你导入模块时,你永远不知道.json 是否准备好了,或者当它没有准备好时如何等待它。所以不要这样做。而是导出一个 Promise(或者更好的是,从你的函数中返回它)。
  • 不要这样做。如果需要持久化到文件系统,请使用fs.writeFile()。不要让您的代码更难理解或违反预期模式。
  • @zero298 仍然有竞争条件;如果他们只需要对动态数据进行操作,我看不出这有什么帮助。
  • @DaveNewton 此代码存在多个问题。我只解决了这样一个事实,即 OP 正试图为某些不应该真正使用的东西超载导出。 Bergi 已经指出了异步问题。整个方法是有缺陷的。
  • @zero298 耸耸肩 我只是看不出涉及文件系统的相关性。 YMMV。

标签: javascript node.js ajax


【解决方案1】:

不,这是不可能的,但是根据我的说法,通过查看您的代码,您正试图将json 发送回给调用getting_order 函数的人。因此,您应该将 回调函数 作为参数传递,并在收到 json 时调用该函数。

const https = require("https");
var json;
function getting_order(callback){

    var options = {
        hostname: "some_url.com",
        port: 443,
        path: "/certain/endpoint/",
        method: "GET"
    };


    var req = https.request(options, (res) => {
        let responseBody = "";

        res.setEncoding("UTF-8");

        res.on('data',(chunk) => {
            responseBody += chunk;
        })

        res.on('end',() =>{
            json = JSON.parse(responseBody)
            callback(json);
        })

    });
    req.end();
};

module.exports.getting_order = 

如何使用上述解决方案

//call like this
getting_order(function(order_json) {
    //you will receive json here
    console.log(order_json);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 2020-12-12
    • 2017-05-18
    相关资源
    最近更新 更多