MoltasDev
MoltasDev

Reputation: 65

fs.readFileSync() no callback and encode doesn't work?

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

Answers (3)

SamiMalik
SamiMalik

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

Gibor
Gibor

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

Terry Lennox
Terry Lennox

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

Related Questions