Node JS FS Module

Let’s Start

In this article, We will learn about Node JS File System

You all know node JS work on event-driven and non-blocking

About Node JS file system: File system in basic operations like read, write, append, delete, close, etc. Node Js provides an inbuilt fs module, all file

system can have synchronously  and asynchronously depending on user requirement

  •  Create an index.js file and data.txt file, data.txt is store our data
  •  Note: readfile, readfilesync, writefile, writefilesync this function does not create a txt file automatic you have to create a txt file only fs.open() function read, write, create file operation can do
  • First Import fs module
const fs = require("fs");
  • Asynchronously read file code 
fs.readFile('data.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});
  • Synchronously read file code
const data = fs.readFileSync('data.txt');
console.log("Synchronous read: " + data.toString());
  • Asynchronously write file code 
fs.writeFile('data.txt', 'The CodeHubs', function(err) {
   if (err) {
      return console.error(err);
   }
});
  • Synchronously write file code
fs.writeFileSync('data.txt', 'The CodeHubs');
  • Asynchronously append file code 
const data = "\nLearn Node js File System";

fs.appendFile('data.txt', data, 'utf8',
    function(err) {
        if (err) throw err;
        console.log("Data is appended to file successfully.")
});
  • Synchronously append file code
const data = "\nLearn Node js File System";
fs.appendFileSync('data.txt', data, 'utf8');
console.log("Data is appended to file successfully.")
  • Open function Node JS File System: Using open function you can do read, write, and create fs.open() function does several operations on file it’ automatically create a file

Syntax: 

fs.open(path, flags, mode, callback)

Parameters:

    • path: It takes a file name and file path
    • flags: Flags indicate the file behavior. just like an ( r, r+, rs, rs+, w, wx, w+, wx+, a, ax, a+, ax+)
    • mode: file indicates different types of mode and you have also set this mode as the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default as read-write
  • Below example of the automatic create the file and write content
fs.open('data2.txt', 'w+', function(err) {
   if (err) {
      return console.error(err);
   }
   fs.writeFileSync('data2.txt','hi how are you all')
   console.log("File open successfully");    
});

 

If you have any query or issue, please let me know

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories