How to read a file as a string in nodejs javascript?


Below code reads the file con­tent in asynchronous man­ner and the con­tent is returned in the string for­mat and buffered for­mat respectively.

let fs = require("fs-extra");
let path = require("path");

fs.readFile(path.join(__dirname, "filePath"), "utf8",(data, err) => {
  console.log(data); // logs file content in string 
});

fs.readFile(path.join(__dirname, "filePath"), (data, err) => {
  console.log(data); // logs file content in buffer
});

Syn­chro­nous version

const str = fs.readFileSync(path.join(__dirname, "filePath"), "utf8");

const buffer = fs.readFileSync(path.join(__dirname, "filePath"));

You may also like...