【问题标题】:Call a function in node.js在 node.js 中调用函数
【发布时间】:2013-11-01 04:55:29
【问题描述】:

我是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 函数。运行此代码时,它只打印 sever running on the port..", not myjson` 的内容。

我知道上面的代码不正确

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

【问题讨论】:

  • 您定义了一个函数,但您没有调用它的语句。添加getData(null);

标签: javascript jquery json node.js


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    不要采取错误的方式,但您的代码似乎是一堆不相关的示例。我建议您先学习 JavaScript 和 node.js 的基础知识(例如,阅读 Eloquent JavaScriptFelix's Node.js Beginners Guide)。


    但是关于你的代码。首先,您正在创建一个函数(称为getData)并将其导出。然后你打印“服务器在端口 9090 上运行”。您的脚本中没有服务器代码,并且您创建的函数永远不会执行。

    我想这是你打算写的:

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

    假设readJSONFile是一个实函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 2014-04-30
      • 1970-01-01
      • 2017-01-09
      • 2020-01-16
      • 1970-01-01
      • 2018-01-11
      • 2018-01-11
      相关资源
      最近更新 更多