I
I
IvankoPo2018-09-13 14:32:59
JavaScript
IvankoPo, 2018-09-13 14:32:59

How to write code for node js?

let obj;
fs.readFile("config.json", (err, data) => {
    if (err){
        console.log(err);
    } else {
        obj = JSON.Parse(data);
    }
});
console.log(obj);

The problem is that obj will be undefined, but I need to somehow work with this variable further, and I don’t want to write huge logic in the else branch of the callback, how is this problem solved? Sync cannot be used.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2018-09-13
@IvankoPo

new Promise((resolve, reject) => {
  fs.readFile("config.json", (err, data) => {
    if(err) {
      return reject(err);
    }
    resolve(JSON.Parse(data));
  });
}).then(obj => {
  console.log(obj);
  // your code
}).catch(console.error);

L
Lynn "Coffee Man", 2018-09-13
@Lynn

Specifically, here it is easier to use synchronous reading of the file, and given that this is generally json, let obj = require('./config.json');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question