i'm pretty new into NodeJs. And i am trying to read a file into a variable. Here is my code.
我是NodeJs的新手。我试图将文件读入变量。这是我的代码。
var fs = require("fs"),
path = require("path"),
util = require("util");
var content;
console.log(content);
fs.readFile(path.join(__dirname,"helpers","test.txt"), 'utf8',function (err,data) {
if (err) {
console.log(err);
process.exit(1);
}
content = util.format(data,"test","test","test");
});
console.log(content);
But every time i run the script i get undefined
and undefined
但每次我运行脚本我都会得到未定义和未定义
What am i missing? Help please!
我错过了什么?请帮助!
1 个解决方案
#1
4
As stated in the comments under your question, node is asynchronous - meaning that your function has not completed execution when your second console.log
function is called.
正如您的问题中的注释所述,节点是异步的 - 这意味着在调用第二个console.log函数时,您的函数尚未完成执行。
If you move the log statement inside the the callback after reading the file, you should see the contents outputted:
如果在读取文件后在回调内移动log语句,则应该看到输出的内容:
var fs = require("fs"),
path = require("path"),
util = require("util");
var content;
console.log(content);
fs.readFile(path.join(__dirname,"helpers","test.txt"), 'utf8',function (err,data) {
if (err) {
console.log(err);
process.exit(1);
}
content = util.format(data,"test","test","test");
console.log(content);
});
Even though this will solve your immediately problem, without an understanding of the async nature of node, you're going to encounter a lot of issues.
即使这将解决您的问题,如果不了解节点的异步性质,您将遇到很多问题。
This similar * answer goes into more details of what other alternatives are available.
这个类似的*答案详细介绍了其他替代方案的可用性。
#1
4
As stated in the comments under your question, node is asynchronous - meaning that your function has not completed execution when your second console.log
function is called.
正如您的问题中的注释所述,节点是异步的 - 这意味着在调用第二个console.log函数时,您的函数尚未完成执行。
If you move the log statement inside the the callback after reading the file, you should see the contents outputted:
如果在读取文件后在回调内移动log语句,则应该看到输出的内容:
var fs = require("fs"),
path = require("path"),
util = require("util");
var content;
console.log(content);
fs.readFile(path.join(__dirname,"helpers","test.txt"), 'utf8',function (err,data) {
if (err) {
console.log(err);
process.exit(1);
}
content = util.format(data,"test","test","test");
console.log(content);
});
Even though this will solve your immediately problem, without an understanding of the async nature of node, you're going to encounter a lot of issues.
即使这将解决您的问题,如果不了解节点的异步性质,您将遇到很多问题。
This similar * answer goes into more details of what other alternatives are available.
这个类似的*答案详细介绍了其他替代方案的可用性。