Node.js Tutorial

Node.js File System (fs) Module

Node.js File System
Node.js File System

Node.js File System

In Node.js, file input and output operations are handled using the built-in File System (fs) module. It provides a simple way to work with files and directories, including reading, writing, opening, updating, and deleting files.

The File System module can be imported using the following syntax:

var fs = require("fs");

Node.js FS Reading a File

Methods in the Node.js fs module are available in both synchronous and asynchronous forms.

  • Asynchronous methods: These methods use a callback and allow other operations to continue while the file operation is in progress. They do not block the Node.js event loop.
  • Synchronous methods: These methods block program execution until the file operation has completed.

Asynchronous file operations are generally preferred in server-side applications because they provide better performance and scalability.

Complete Advance AI Topics: Click Here
SQL Tutorial:
Click Here

Example: Reading a File in Node.js

First, create a text file named input.txt and add the following content:

File: input.txt

UpdateGadh is one of the best online tutorial websites to learn different technologies
in a very easy and efficient manner.

Now create a JavaScript file named main.js and add the following code:

File: main.js

var fs = require("fs");

// Asynchronous read
fs.readFile('input.txt', function (err, data) {
   if (err) {
       return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});

// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());

console.log("Program Ended");

Run the program from the Node.js terminal using:

node main.js

Node.js Opening a File

The fs.open() method can be used to open a file asynchronously.

Syntax:

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

Parameters of fs.open()

  • path: Specifies the name or path of the file.
  • flags: Specifies how the file should be opened, such as for reading, writing, or appending.
  • mode: Defines file permissions. The default value is 0666.
  • callback: A function that receives err and fd, where fd is the file descriptor.

Common File Open Flags

FlagDescription
rOpens the file for reading. An error occurs if the file does not exist.
r+Opens the file for reading and writing. An error occurs if the file does not exist.
rsOpens the file for reading in synchronous mode.
rs+Opens the file for reading and writing in synchronous mode.
wOpens the file for writing. Creates the file if it does not exist or truncates it if it already exists.
wxWorks like w, but fails if the file already exists.
w+Opens the file for reading and writing. Creates or truncates the file as needed.
wx+Works like w+, but fails if the file already exists.
aOpens the file for appending. Creates the file if it does not exist.
axWorks like a, but fails if the file already exists.
a+Opens the file for reading and appending. Creates the file if it does not exist.
ax+Works like a+, but fails if the file already exists.

Example: Opening a File Asynchronously

File: main.js

var fs = require("fs");

console.log("Going to open file!");

fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
       return console.error(err);
   }

   console.log("File opened successfully!");
});

Run the program using:

node main.js

Node.js File Information

The fs.stat() method can be used to retrieve detailed information about a file or directory.

Syntax:

fs.stat(path, callback)

Parameters of fs.stat()

  • path: Specifies the name or path of the file.
  • callback: A function that receives err and stats. The stats object is an instance of fs.Stats and provides information about the file.

Common fs.Stats Methods

MethodDescription
stats.isFile()Returns true if the path represents a regular file.
stats.isDirectory()Returns true if the path represents a directory.
stats.isBlockDevice()Returns true if the path represents a block device.
stats.isCharacterDevice()Returns true if the path represents a character device.
stats.isSymbolicLink()Returns true if the path represents a symbolic link.
stats.isFIFO()Returns true if the path represents a FIFO.
stats.isSocket()Returns true if the path represents a socket.

Example: Getting File Information

YT:- DecodeIT

File: main.js

var fs = require("fs");

console.log("Going to get file info!");

fs.stat('input.txt', function (err, stats) {
   if (err) {
       return console.error(err);
   }

   console.log(stats);
   console.log("Got file info successfully!");
   console.log("isFile ? " + stats.isFile());
   console.log("isDirectory ? " + stats.isDirectory());
});

Run the script using:

node main.js

Conclusion

The Node.js fs module provides essential functionality for working with files and directories. Using methods such as readFile(), readFileSync(), open(), and stat(), developers can efficiently read files, open file descriptors, and retrieve file information in Node.js applications.

Keywords

Node.js File System, Node.js fs module, Node.js File System Module, Node.js fs, Node.js read file, Node.js open file, Node.js file information, Node.js fs.stat, Node.js fs.open, Node.js file handling, Node.js file operations, Node.js tutorial Node.js File System, Node.js fs Module, Node.js File System Module, Node.js fs, Node.js File Handling, Node.js Read File, Node.js Open File, Node.js fs.stat, Node.js fs.open, Node.js File Operations, Node.js Tutorial

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

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

Chat with us