Open In App

How to use the fs module in Node ?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The fs module in NodeJS provides an interface for working with the file system. It allows you to perform various operations such as reading from and writing to files, manipulating directories, and handling file permissions.

What is the fs Module?

The fs module is a built-in module in NodeJS that provides file system-related functionality. It allows you to interact with the file system in a non-blocking, asynchronous manner, making it well-suited for I/O operations in NodeJS applications.

Why Use the fs Module?

The fs module is essential for performing file system operations in NodeJS applications. Whether you need to read configuration files, write log files, or serve static assets, the fs module provides the necessary tools to interact with the file system efficiently.

How to Use the fs Module ?

The fs module provides a wide range of functions for working with files and directories. Some of the most commonly used functions include:

  • fs.readFile(): Reads the contents of a file asynchronously.
  • fs.writeFile(): Writes data to a file asynchronously, replacing the file if it already exists.
  • fs.appendFile(): Appends data to a file asynchronously, creating the file if it does not exist.
  • fs.readdir(): Reads the contents of a directory asynchronously.
  • fs.stat(): Retrieves information about a file asynchronously, such as its size, permissions, and timestamps.
  • fs.unlink(): Deletes a file asynchronously.
  • fs.mkdir(): Creates a directory asynchronously.
  • fs.rmdir(): Removes a directory asynchronously.

Example: In this example, fs.readFile() is used to asynchronously read the contents of a file named example.txt, while fs.writeFile() is used to asynchronously write data to the same file.

const fs = require('fs');

// Read from a file
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

// Write to a file
fs.writeFile('example.txt', 'Hello, world!', (err) => {
if (err) throw err;
console.log('File written successfully');
});

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads