DEV Community

Cover image for Reading files with Node.js
Mrityunjay-Palled
Mrityunjay-Palled

Posted on

Reading files with Node.js

As we know, reading the content of a file is one of the most common and important tasks of programming. Let's take a look at how we can read files in node.js.

Using readFile():

readFile takes three parameters, and they are:

path: Filepath of the file to read
encoding: It is an optional parameter; possible values are ascii, utf8,and base64.
callback: It is passed with two arguments: error and data,error contains the error message, and data contains the data coming from the file.
readFile is asynchronous in nature; therefore, it will not interrupt the execution of the program.

//importing file system module 
const fs=require('fs')
const path='./myFiles/read.txt'
fs.readFile(path,'utf8',(err,data)=>{
    if(err)return console.log("error occured while reading data");
    console.log(data);
})
Enter fullscreen mode Exit fullscreen mode

output in the console is as shown below

Hello from read.txt
Enter fullscreen mode Exit fullscreen mode

without 'utf8' encoding then output will be raw buffer data

<Buffer 48 65 6c 6c 6f 20 66 72 6f 6d 20 72 65 61 64 2e 74 78 74>
Enter fullscreen mode Exit fullscreen mode

using readFileSync():

readFileSync takes two parameters, and they are:

path: Filepath of the file to read
encoding: It is an optional parameter; possible values are ascii, utf8,and base64.

readFileSync is synchronous in nature, which means the rest of the code execution will be stopped until the file is read completely.

//importing file system module
const fs = require("fs");
const path = "./myFiles/read.txt";
try {
  const data = fs.readFileSync(path, 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}
Enter fullscreen mode Exit fullscreen mode

output in the console is as shown below

Hello from read.txt
Enter fullscreen mode Exit fullscreen mode

Using promise-based readFile():

Promise-based readFile takes two parameters, and they are:

path: Filepath of the file to read
encoding: It is an optional parameter; possible values are ascii, utf8,and base64.

since it is promise-based we can use async-await.

//importing promise-based file system module
const fsPromise = require("fs").promises;
const path = "./myFiles/read.txt";

const fileRead = async () => {
  try {
    const data = await fsPromise.readFile(path, "utf8");
    console.log(data);
  } catch (err) {
    console.error(err);
  }
};

fileRead();
Enter fullscreen mode Exit fullscreen mode

output in the console is as shown below

Hello from read.txt
Enter fullscreen mode Exit fullscreen mode

Top comments (0)