Aung Htet Paing
Aung Htet Paing

Reputation: 131

How to get callback data from nodejs module exports function

i can not get data from callback function at nodejs. data is undefined..

const fs = require('fs');
module.exports.license = fs.readFile('license.json', (err,data) => {
if(err){
  return err;
} else { return data; }
});

const boot = require('./boot');
console.log(boot.license);

Upvotes: 1

Views: 79

Answers (1)

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

Your code needs to be changed a little bit if you want it to work:

const fs = require('fs');

module.exports.license = function license(cb) {
  fs.readFile("license.json", cb);
}

Now in your main module, you will use it as follows:

const boot = require('./boot');

boot.license((err, data) => {
  if (err) console.err(err);
  console.log(data);
});

The idea is that you will need to pass the callback as function parameter where you will get the data or the error; A decent article on Callbacks explained in plain english.

Upvotes: 1

Related Questions