0

I have the below function, which reads text from a file and outputs the text into the data variable.

fs.readFile('a1.txt', 'utf8', function(err, data) {  

   if (err) throw err;
   console.log(data);
});

I want to assign data to a global variable so i can use it in other parts of my program. at the moment I am unable to use the information taken from data. What can I do to store data into another variable which i can use freely in other functions?

DelsE
  • 1
  • 1
  • 2
    It's easy to assign it to a global variable, use `someGlobalVar = data`. But that's different from *consuming* the data asynchronously, which *can't* be done on the global level - you'll have to wrap the whole thing in an async function or use `.then` or a callback. – CertainPerformance Apr 11 '18 at 04:29
  • Since you are targeting a CommonJS environment, attaching a property to `module.exports` makes a lot more sense than an actual global. That said, it doesn't sound like your really want a variable as much as that you don't understand how callbacks work. Take a look at [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Aluan Haddad Apr 11 '18 at 04:44

1 Answers1

1

What you're asking for is not really global, just a higher scope than the function.

Seeing as you're in node.js, you can just put a variable at the top of your file (or wherever):

var a1Data;

then just use a1Data = data in the callback.

If you truly want something global, you can use global.whatever = data, but that's typically not what you want.

whitfin
  • 4,539
  • 6
  • 39
  • 67
  • not to mention that `readFile` is asynchronous so using the global variable after the call might stuff up the rest of the application. – Jorg Apr 11 '18 at 04:47
  • Yes and no; just because something is asynchronous doesn't mean you can't guarantee that you're only using it when it's initialized correctly. – whitfin Apr 11 '18 at 04:50
  • Will I be able to use a1Data in other functions? – DelsE Apr 11 '18 at 04:57
  • When I try that, it gives me an undefined message. – DelsE Apr 11 '18 at 05:05
  • @DelsE Yes, because that's global. I would need to see more code to debug what you're doing to cause the undefined issue though. – whitfin Apr 13 '18 at 01:54