0

I'm trying to set value in a global variable result but it's returning undefined Please find my code below:

myFile.js

const fs = require('fs');

var result
async function processFile(fileName) {

    fs.readFile(fileName, (err, data) => {
        if (err) throw err;
        let student = JSON.parse(data);
        //console.log(student);
        result = student;
    });
}
processFile('src/file.json')
console.log('Get Results')
console.log(result)

file.json

{ 
    "name": "Sara",
    "age": 23,
    "gender": "Female",
    "department": "History",
    "car": "Honda"
}

I'm not sure why this one result = student; is not setting in a global variable. Could you please help me with this? I would like access result variables in multiple places.

Thanks

Mike Marsh
  • 387
  • 3
  • 15
  • It is setting the global variable... but in the _future_. Any result from an asynchronous call should be used in the callback or `.then` handler of such a function (or a consequence of those). – Amadan Jun 18 '21 at 03:48
  • how to get that.. sorry I'm new to NodeJs so having some difficulty to understanding this. – Mike Marsh Jun 18 '21 at 03:49
  • See the linked question, it goes in quite a bit of detal. tl;dr: you can't do what you are trying to do. The commented-out `console.log` is the correct place to use `student`. – Amadan Jun 18 '21 at 03:52
  • Yes, but I need the student value outside of the function :( – Mike Marsh Jun 18 '21 at 03:56
  • You only think you do; and as long as you continue to think so, you will not progress much with Node.js. I assure you that there is a way to rewrite your code so that `student` is either used inside the callback, or as a consequence of the callback. You haven't said anything about _why_ you need it outside, or what you intend to do with it, so it is not really possible for me to give you any more detailed answer than "read the linked question". – Amadan Jun 18 '21 at 03:59

1 Answers1

0

const fs = require('fs');

var result
async function processFile(fileName) {
  result = fs.readFileSync(fileName, {
    encoding: 'utf8'
  });
}
processFile('src/file.json')
console.log('Get Results')
console.log(result)

take a try enter image description here

bin liu
  • 227
  • 1
  • 6
  • Nope - this one not working – Mike Marsh Jun 18 '21 at 03:54
  • 1
    This absolutely does work. Make sure you notice the change from `readFile` to `readFileSync`. Moving to synchronous functions is one option, where available. However, it has two drawbacks: 1) it impacts performance, and 2) not all asynchronous concepts have synchronous equivalents in node; learning about asynchronicity is very important when learning Node.js. – Amadan Jun 18 '21 at 03:58
  • but I got it;@MikeMarsh – bin liu Jun 18 '21 at 04:01
  • does this answer cannot fit you? – bin liu Jun 21 '21 at 07:52