0

I have found many variations of this question, but none seem to answer my question. I read How do I define a nodejs variable using a function? among many other answers. I tried all of the possible answers using an asynchronous call. It is possible that the answer is in there, but I implemented it wrong.

I am able to get the console.dir command to work inside the function. I am having trouble understanding how to get the console.dir function to work outside of the function.

I would like to set the variable "library" using the contents of a file using the nodejs function fs.readFile. This is what I have, but it does not work.

This seems like such a simple problem, so I am certain I just do not understand callbacks or some universal concept. I have been searching Stackoverflow and the web all day.

var library = fs.readFile('./library', function read(err, data) {
    if (err) {
        throw err;
    }

    return data
});

console.dir(library);

the return is:

undefined

user3877654
  • 1,045
  • 1
  • 16
  • 40
  • in your particual case `fs.readFileSync` would do the trick (though not recommended) – Aritra Chakraborty Jul 22 '19 at 21:43
  • @VLAZ, I have modified my question to include your answer. I read How do I define a nodejs variable using a function? among many other answers. I tried all of the possible answers using an asynchronous call. It is possible that the answer is in there, but I implemented it wrong. I am able to get the console.dir command to work inside the function. I am having trouble understanding how to get the console.dir function to work outside of the function. – user3877654 Jul 22 '19 at 21:53
  • @AritraChakraborty Thank you for your answer, but I am interested in asynchronous methods. – user3877654 Jul 22 '19 at 21:54
  • Please stop writing `if (err) throw err` inside an asynchronous callback. It does you absolutely no good at all. The exception just goes back into the file system async infrastructure where you can do nothing with it. Write real error handling code. – jfriend00 Jul 23 '19 at 00:04

0 Answers0