Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function in node.js

I am new to node.js .Here I write a sample function in node.js to print the contents of a json file as follows.

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

What I am doing here is I just want to read a json file and print the contents in console. But I do not know how to call the getData function. While running this code it only prints the sever running on the port..", not myjson` contents.

I know the above code is not correct

How can I call a function in node.js and print the json contents?

like image 822
Sush Avatar asked Nov 27 '25 02:11

Sush


1 Answers

Node.js is just regular javascript. First off, it seems like you are missing a }. Since it makes the question easier to understand, I will assume that your console.log("Server... is outside exports.getData.

You would just call your function like any other:

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

I would note that you have a callback argument in your getData function but you are not calling it. Perhaps it is meant to be called like so:

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

Truthfully, your getData function is a little redundant without any more content to it since it does nothing more than just wrap readJSONFile.

like image 139
Los Frijoles Avatar answered Nov 28 '25 14:11

Los Frijoles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!