简体   繁体   English

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

[英]Node.js - accessing a const from a function within http.get

In the code below I am accessing the current bitcoin value in GBP.在下面的代码中,我以英镑访问当前的比特币价值。 The console.log works fine. console.log 工作正常。

value.js值.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;
            });
    }
);

However when I try to access this value (final_value) from another file:但是,当我尝试从另一个文件访问此值 (final_value) 时:

server.js服务器.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);
});

All I get back is {}.我得到的只是 {}。

I'm quite new to node.js and more used to python.我对 node.js 很陌生,更习惯于 python。 I've looked into accessing values from functions within functions but couldn't find any kind of solution.我研究了从函数内的函数访问值,但找不到任何解决方案。

Does anyone have a recommendation as to how I could access the variable final_value from a separate file?有没有人建议我如何从单独的文件访问变量 final_value?

I honestly prefer to use express than native Node, but given that you are using it, I can give you some tips to help you with it:老实说,我更喜欢使用 express 而不是原生 Node,但是鉴于您正在使用它,我可以给您一些提示来帮助您:

If you want to use a js file from other, you should export what you want to share between them.如果要使用其他人的 js 文件,则应导出要在它们之间共享的内容。 In the example that you are showing it should be something like this (note that I'm exporting the function and also using it as a Promise in a function):在您展示的示例中,它应该是这样的(请注意,我正在导出函数并将其用作函数中的 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);
                });
            }
        );
    });
}

then you can use it in your server file in this way:那么您可以通过这种方式在您的服务器文件中使用它:

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

You can change module.exports = final_value to exports.final_value = final_value , and then retrieve the value with您可以将module.exports = final_value更改module.exports = final_value exports.final_value = final_value ,然后使用

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

...

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

The advantage of this is that you can now export other values from the value.js file, and just require them in the same way.这样做的好处是您现在可以从value.js文件中导出其他值,只需以相同的方式要求它们。 The main difference between module.exports and exports.value is that module.exports is an object that has exports as a property, and exports is just an alias for module.exports .之间的主要区别module.exportsexports.valuemodule.exports是具有对象exports作为一个属性, exports仅仅是一个别名module.exports Essentially, by using the module.exports syntax, you are assigning module.exports the value of the object you are assigning to it.本质上,通过使用module.exports语法,您正在为module.exports分配您分配给它的对象的值。

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

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