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



在下面的代码中,我正在访问以英镑为单位的当前比特币价值。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而不是原生Node,但鉴于您正在使用它,我可以给您一些提示来帮助您:

如果你想使用其他人的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只是module.exports的别名。从本质上讲,通过使用module.exports语法,您将为module.exports分配对象的值

最新更新