简体   繁体   中英

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.

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;
            });
    }
);

However when I try to access this value (final_value) from another file:

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);
});

All I get back is {}.

I'm quite new to node.js and more used to 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?

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:

If you want to use a js file from other, you should export what you want to share between them. 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):

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

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. 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 . Essentially, by using the module.exports syntax, you are assigning module.exports the value of the object you are assigning to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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