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

ⅰ亾dé卋堺 提交于 2019-12-09 06:02:44

问题


I'm wondering if its 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 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

Thanks


回答1:


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();


来源:https://stackoverflow.com/questions/18494226/storing-nodejs-fs-readfiles-result-in-a-variable-and-pass-to-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!