0

In the same folder I have 3 different files with the following content :
• index.js

const getToken = require('./getToken.js');
console.log(getToken.getToken());

• getToken.js

const FS = require('fs'); //a library to read files    
module.exports = {
    getToken: function (){
        FS.readFile('./token.txt', 'utf8', function (err, data) {
            if (err) {
                console.error(err);
            } else {
                console.log('Token is : ' + data);
                return data;
            }
        });
    }
}

• token.txt

foo

I'm using NodeJs, fs, a library to read files and a Discord library.
I get as output :

undefined //result of index.js
Token is : foo //result of getToken.js

The code is working fine except that the token isn't given correctly to the main js file (index.js) even if it's read properly.
What's wrong with this code? Why do the results of console.log() are in the wrong ordrer?

Thanks.

0

1 Answer 1

2

Welcome to the async world. You need to use callbacks or promises when returning values after an async operation (fs.readFile is async);

Using callback would be like this:

module.exports = {
    getToken: function (callback){
        FS.readFile('./token.txt', 'utf8', function (err, data) {
            if (err) {
                callback(err);
            } else {
                console.log('Token is : ' + data);
                callback(null, data);
            }
        });
    }
}


//Other file
const getToken = require('./getToken.js');

getToken.getToken(function(err, result){
  if(err) return console.log(err);
  console.log(result);
});
1
  • Tahnks, didn't know this was an async function that needed a callback... It wasn't explicitly said.
    – Ascor8522
    Jan 2, 2018 at 21:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.