Node.js-从http.get中的函数访问const

问题描述

在下面的代码中,我正在访问GBP中的当前比特币值。 console.log可以正常工作。

value.js

http = require('http');

http.get({
    host: 'api.coindesk.com',path: '/v1/bpi/currentprice.json'
    },function get_value(response) {
        // Continuously update stream with data
        var body = '';
        response.on('data',function(d) { body += d; });
        response.on('end',function() {
                 // Data reception is done,do whatever with it!
                var parsed = JSON.parse(body);
                var final_value = parsed.bpi.GBP.rate
                console.log(final_value)
                module.exports = final_value;
            });
    }
);

但是,当我尝试从另一个文件访问该值(final_value)时:

server.js

PORT = 4000;
var http = require('http');
const value = require('./value.js');

var server = http.createServer((req,res) => {
    res.write("Create server working");
});

server.listen(PORT,() => {
    console.log(value);
});

我得到的只是{}。

我对node.js很陌生,对python更熟悉。我已经研究过从函数中的函数访问值,但是找不到任何解决方案。

有人建议我如何从单独的文件访问变量final_value吗?

解决方法

老实说,我比本地节点更喜欢使用express,但是鉴于您正在使用它,我可以为您提供一些技巧来帮助您:

如果要使用其他js文件,则应导出要在它们之间共享的内容。在显示的示例中,它应该是这样的(请注意,我正在导出该函数,并且还将其用作函数中的Promise):

const http = require('http');

module.export = function () {
    return new Promise(function (resolve) {
        http.get({
                host: 'api.coindesk.com',path: '/v1/bpi/currentprice.json'
            },function get_value(response) {
                // Continuously update stream with data
                var body = '';
                response.on('data',function(d) { body += d; });
                response.on('end',function() {
                    // Data reception is done,do whatever with it!
                    var parsed = JSON.parse(body);
                    var final_value = parsed.bpi.GBP.rate
                    console.log(final_value)
                    resolve(final_value);
                });
            }
        );
    });
}

然后您可以通过以下方式在服务器文件中使用它:

...
server.listen(PORT,() => {
    value.then(result => console.log(result));
});
,

您可以将module.exports = final_value更改为exports.final_value = final_value,然后使用来检索值

const { final_value } = require('./value.js');

...

server.listen(PORT,() => {
    console.log(final_value);
});

这样做的好处是,您现在可以从value.js文件中导出其他值,并且只需以相同的方式要求它们即可。 module.exportsexports.value之间的主要区别在于module.exports是具有exports作为属性的对象,而exports只是{{1 }}。本质上,通过使用module.exports语法,您正在为module.exports分配要为其分配的对象的值。