gpt4 book ai didi

javascript - 在 node.js 中调用一个函数

转载 作者:搜寻专家 更新时间:2023-10-31 23:33:18 25 4
gpt4 key购买 nike

我是 node.js 的新手。这里我在 node.js 中编写了一个示例函数来打印 json 文件的内容,如下所示。

exports.getData =function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
console.log(json);

});
console.log("Server running on the port 9090");

我在这里所做的只是想读取一个 json 文件并在控制台中打印内容。但我不知道如何调用 getData 函数。运行此代码时,它只打印 在端口上运行的服务器..",而不是我的json` 内容。

我知道上面的代码不正确

如何调用 node.js 中的函数并打印 json 内容?

最佳答案

Node.js 只是普通的 javascript。首先,您似乎缺少 }。因为它使问题更容易理解,所以我假设您的 console.log("Server...exports.getData 之外。

您只需像调用任何其他函数一样调用您的函数:

...
console.log("Server running on the port 9090");
exports.getData();

我会注意到您的 getData 函数中有一个 callback 参数,但您没有调用它。也许它应该这样称呼:

exports.getData = function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
callback(json);
});
}
console.log("Server running on the port 9090");
exports.getData(function (json) {
console.log(json);
});

说实话,您的 getData 函数有点多余,没有任何内容,因为它只是包装 readJSONFile

关于javascript - 在 node.js 中调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com