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

后端 未结 1 1975
孤街浪徒
孤街浪徒 2021-02-05 18:24

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;

functi         


        
相关标签:
1条回答
  • 2021-02-05 19:17

    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();
    
    0 讨论(0)
提交回复
热议问题