Reputation: 65
I wrote this little test code in an attempt to debug another project of mine and discovered that fs.readFileSync() appears to have no callback function and encoding doesn't work.
const fs = require("fs");
var x = fs.readFileSync(__dirname + "/file.txt", {encode: "utf8"}, () => {
console.log("Callback function?");
});
console.log(x);
Expected output: "Callback function?" content of file.txt
But I simply recieved ""
What is wrong here?
Upvotes: 1
Views: 3215
Reputation: 160
I am not sure either you want synchronous operations in Node.js or asynchronous, but I see you are using synchronous function fs.readFileSync, and trying to access via async approach
For reading a file you can use the readFileSync method of the fs class: like
const fs = require("fs");
const output = fs.readFileSync(__dirname + "/file.txt");
console.log(output);
For getting data asynchronously, you will get content in call back.
fs.readFile(filename, "utf8", (err, data) => {
if (err) throw err;
console.log(data)
});
Upvotes: 1
Reputation: 1721
Take a look at documentation here. It clearly shows no callback, and I guess the call doesn't work because you gave a function instead of the "flags" option and it kinda messed it up.
Also, this is called "readFileSYNC" - Synchronous actions by default does not have a callback, you can just write what you want to happen right after them- and it will happen right after them. No timing issues because again- they are synchronous.
The right code for your program would be:
var x = fs.readFileSync(__dirname + "/file.txt", { encoding: "utf8" });
, and after this log w/e you want or do with data w/e you want, it will be inside X variable.
Upvotes: 3
Reputation: 30715
fs.readFileSync doesn't take a callback, since it runs synchronously. It will return the file data.
If you do wish to read a file asynchronously, use fs.readFile.
Here's an example of both:
// Sync. readFile
const fileData = fs.readFileSync("some_file.txt", { encoding: "utf8"});
console.log("fileData:", fileData);
// Async. readFile
fs.readFile("some_file.txt", { encoding: "utf8"}, (err, fileData) => {
if (err) {
console.error("Error occurred:", err);
} else {
console.log("fileData:", fileData);
}
});
Upvotes: 0