0

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 ;

} 

2 Answers 2

1

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)
})
Sign up to request clarification or add additional context in comments.

1 Comment

I am not exactly sure what you are asking, could you clarify pls?
0

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

2 Comments

yeah, I have tried this, but when I start to work with the json that is been returned due to asynchronous behavior of node, since jsn read before json returns met error.. so I tried to use then
readFileSync is asnychronous, it will block execution until the content is read

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.