22

I'm wondering if it's possible to pass the contents of fs.readfile out of the scope of the readfile method and store it in a variable similar to.

var a;

function b () {
    var c = "from scope of b";
    a = c;
}
b();

Then I can console.log(a); or pass it to another variable.

My question:

Is there a way to do this with fs.readFile so that the contents (data) get passed to the global variable global_data.

var fs = require("fs");

var global_data;

fs.readFile("example.txt", "UTF8", function(err, data) {
    if (err) { throw err };
    global_data = data;
});

console.log(global_data);  // undefined
Pradeep Singh
  • 1,094
  • 1
  • 9
  • 24
Paul
  • 263
  • 1
  • 3
  • 6
  • 3
    Welcome to the wonderful world of **async**! You can't do that. – SLaks Aug 28 '13 at 17:17
  • 1
    You are trying to access something from an asynchronous context in a synchronous one, which doesn't work, here a pic (read the comment below, too) : https://stackoverflow.com/a/34161451/5925094 – Rich Steinmetz Jul 06 '20 at 19:18

1 Answers1

43

The problem you have isn't a problem of scope but of order of operations.

As readFile is asynchronous, console.log(global_data); occurs before the reading, and before the global_data = data; line is executed.

The right way is this :

fs.readFile("example.txt", "UTF8", function(err, data) {
    if (err) { throw err };
    global_data = data;
    console.log(global_data);
});

In a simple program (usually not a web server), you might also want to use the synchronous operation readFileSync but it's generally preferable not to stop the execution.

Using readFileSync, you would do

var global_data = fs.readFileSync("example.txt").toString();
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Right Im just wondering if its possible to pass data variable contents to the global global_data variable. The console.log(global_data) was just to show that it comes up undefined. – Paul Aug 28 '13 at 17:31
  • I think you didn't understand my answer. It's possible to pass data variable contents to the global global_data variable, there's no problem in that. But the problem you have is that you execute the console.log before you fill the variable. – Denys Séguret Aug 28 '13 at 17:33
  • 1
    Ok, so that's the whole asynchronous thing. But using readFileSync doesn't seem to help. Is it possible to fill the variable before executing console.log. I guess is my question. – Paul Aug 28 '13 at 17:39
  • @DenysSéguret Using readFileSync and converting to string doesnt help since my content in object. – crazyCoder Jul 18 '19 at 02:39