learnNcode
learnNcode

Reputation: 149

How to return back a data from a function and use in nodejs

I was trying to read and file by using a function and need to print that data from main code. Below shown is my code.

getJsonData().then(function (jsonData) {
console.log(jsonData)
})

function getJsonData(){
  var fs = require('fs');
  var XLSX = require('xlsx');
  let contents = fs.readFileSync("test.json");
  let jsonData = JSON.parse(contents);
  return jsonData ;

} 

Upvotes: 0

Views: 44

Answers (2)

ca1c
ca1c

Reputation: 1295

Ok first of All, that function isn't a promise, so you can't use .then. Here is how you would turn this code into a promise:

    var fs = require('fs');
    var XLSX = require('xlsx');

    function getJsonData(){
      return new Promise((resolve, reject) => {
        let contents = fs.readFileSync("test.json");
        if(contents == "undefined") {
          reject("File contains no contents");
        } else {
            let jsonData = JSON.parse(contents);
            resolve(jsonData);
        }
      })  


}

You would then use the function like you did in the question:

getJsonData().then(function (jsonData) {
  console.log(jsonData)
})

Upvotes: 1

Big Money
Big Money

Reputation: 10098

readFileSync doesn't return a promise, so you can't use .then() after getJsonData(), as getJsonData() doesn't return a promise.

You can simply use:

const fs = require('fs');

const results = getJsonData();
console.log(results);

function getJsonData() {
  const contents = fs.readFileSync("test.json");
  return JSON.parse(contents);
}

Upvotes: 0

Related Questions