How to read file to variable in NodeJs?
node.js
Solution
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.
If you move the log statement inside the the callback after reading the file, you should see the contents outputted:
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 stackoverflow answer goes into more details of what other alternatives are available.
Problem
i'm pretty new into NodeJs. And i am trying to read a file into a variable. Here is my code. ``` 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!