fbpx

File read & write in nodejs

The processing of a file is one of the important tasks in programming. We have to read or write to process or processed data. Node provides built-in support to perform various operations on file in which file reading and writing are two tasks. The module provides by node js for file processing is ‘fs‘.

Here we will see the various ways to handle read and write operation on file using fs.writeFile and fs.ReadFile

1. Using a callback

fs.readFile

Function description:

readFile(path: string | number | Buffer | URL, options: string | {
    encoding: BufferEncoding;
    flag?: string;
}, callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void): void 

@param path
A path to a file. If a URL is provided, it must use the file: protocol. URL support is experimental. If a file descriptor is provided, the underlying file will not be closed automatically.

@param options
Either the encoding for the result or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'.

Asynchronously reads the entire contents of a file.

Example

const fs = require("fs");
// contenten of file -> Hi I am reading file using js.
fs.readFile("abc.txt", function (err, data) {
  if (err) {
    console.log({ err });
  } else {
    console.log({ data }); // As we did not passed any encoding so it will return buffer
  }
});

/*output

{
  data: <Buffer 48 69 20 49 20 61 6d 20 72 65 61 64 69 6e 67 20 66 69 6c 65 20 75 73 69 6e 67 20 6a 73 2e>
} */

With encoding argument

fs.readFile("abc.txt", 'utf-8', function (err, data) {
  if (err) {
    console.log({ err });
  } else {
    console.log({ data });
  }
});

/*
{ data: 'Hi I am reading file using js.' }
*/

fs.writeFile

Function description

writeFile(path: string | number | Buffer | URL, data: string | Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array | DataView, options: WriteFileOptions, callback: NoParamCallback): void

@param path
A path to a file. If a URL is provided, it must use the file: protocol. URL support is experimental. If a file descriptor is provided, the underlying file will not be closed automatically.

@param data — The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.

Asynchronously writes data to a file, replacing the file if it already exists.

Example

const fs = require("fs");
fs.writeFile('bca.txt','Hi I am wrking on it', function(err) {
    console.error(err);
})

Using Promise:

  • Without any library

File Read Example

let fs = require("fs");

function readTheFile() {
  return new Promise((resolve, reject) => {
    fs.readFile("abc.txt", "utf-8", function (err, data) {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
}

readTheFile()
  .then((data) => {
    console.log({ data });
  })
  .catch((err) => {
    console.log({ err });
  });

File Write Example

function writeTheFile() {
  return new Promise((resolve, reject) => {
    fs.writeFile("abcd.txt", "We are done", function (err) {
      if (err) {
        reject(err);
      } else {
        resolve('File write done.');
      }
    });
  });
}

writeTheFile()
  .then((data) => {
    console.log({ data });
  })
  .catch((err) => {
    console.log({ err });
  });
  • Using util module

File Read Example

const util = require('util');
let fs = require("fs");

let readFilePromise = util.promisify(fs.readFile)
readFilePromise('abc.txt', 'utf-8').then((data) => console.log({data}))
/*
output
{ data: 'Hi I am reading file using js.' }
*/

File Write Example

const util = require("util");
const fs = require('fs');

let writeFilePromise = util.promisify(fs.writeFile);
writeFilePromise("abc.txt", "I am writing file.")
  .then(() => console.log('File writing done'))
  .catch((err) => {
    console.log(err);
  });
  • Using fs.promises (available in node v10+)

Reading File Example

const fs = require('fs');
fs.promises.readFile('abc.txt', 'utf-8').then((data) => console.log({data}));

/*
output
{ data: 'Hi I am reading file using js.' }
*/

Writing File Example

fs.promises.writeFile("bcd.txt", "I am writing file.")
  .then(() => console.log('File writing done'))
  .catch((err) => {
    console.log(err);
  });