Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing nodejs fs.readfile's result in a variable and pass to global variable

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
like image 868
Paul Avatar asked Aug 28 '13 17:08

Paul


People also ask

How do I store a global variable in node JS?

To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value.

What is the difference between readFile and readFileSync in node JS?

In fs. readFile() method, we can read a file in a non-blocking asynchronous way, but in fs. readFileSync() method, we can read files in a synchronous way, i.e. we are telling node. js to block other parallel process and do the current file reading process.


1 Answers

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();
like image 121
Denys Séguret Avatar answered Sep 22 '22 13:09

Denys Séguret