javascript 将 nodejs fs.readfile 的结果存储在一个变量中并传递给全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18494226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing nodejs fs.readfile's result in a variable and pass to global variable
提问by Paul
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.
我想知道是否可以将 fs.readfile 的内容传递到 readfile 方法的范围之外,并将其存储在类似于的变量中。
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.
然后我可以 console.log(a); 或将其传递给另一个变量。
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.
我的问题是有没有办法用 fs.readFile 做到这一点,以便将内容(数据)传递给全局变量 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
谢谢
回答by Denys Séguret
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.
由于 readFile 是异步的,console.log(global_data);
发生在读取之前,并且global_data = data;
在行执行之前。
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 readFileSyncbut it's generally preferable not to stop the execution.
在一个简单的程序(通常不是 Web 服务器)中,您可能还想使用同步操作readFileSync但通常最好不要停止执行。
Using readFileSync, you would do
使用 readFileSync,你会做
var global_data = fs.readFileSync("example.txt").toString();