Node.js File System with Examples

node js file system

Node.js file system lets you read, write, update, and manage files and folders with built-in methods.

Understand the Node.js File System

Node.js file system is a built-in part of Node.js. It lets you handle files and folders without extra packages.

The file system in Node.js allows you to create and edit files. It also helps you to read files and control folders with app development.

Here is a quick example:

const fs = require('fs');

fs.writeFile('example.txt', 'Hello Node', (err) => {
  if (err) throw err;
  console.log('File created and text written');
});

This code uses writeFile to create a file named example.txt. It writes a message to the file and shows a success message in the console.

Common FS Methods

Below are the most used fs methods. Each method has an example and an explanation.

fs.readFile:

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

This code reads the file content and shows it in the console. It uses UTF-8 for text format.

fs.writeFile:

fs.writeFile('newfile.txt', 'New text here', (err) => {
  if (err) throw err;
  console.log('New file saved');
});

This code creates or updates a file with new text and confirms success in the console.

fs.appendFile:

fs.appendFile('example.txt', '\nExtra text', (err) => {
  if (err) throw err;
  console.log('Text added');
});

This adds extra text to the found file without deleting the previous content.

fs.unlink:

fs.unlink('oldfile.txt', (err) => {
  if (err) throw err;
  console.log('File deleted');
});

This deletes a file by name and confirms removal after success.

Synchronous vs Asynchronous File Handling

Asynchronous calls let Node.js handle other tasks during file operations. This prevents blocking and speeds up the app.

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

This code reads the file content and prints it later. Node.js can run other tasks during this time.

Synchronous calls block other tasks until the file operation ends. This can slow an app with many requests.

const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);

This code waits until the file is fully read before moving to the next line.

Here is a table showing you the key differences:

AspectAsynchronousSynchronous
BlockingDoes not block other tasksBlocks other tasks
Speed in high loadFasterSlower
Code styleUses callbacks or promisesDirect result

Use asynchronous calls for apps with many users at once. Use synchronous calls for simple scripts or startup tasks.

File Path and Directory Operations

Node.js can work with full paths and folders. It can also make, read, or delete folders.

Create folder example:

fs.mkdir('newFolder', (err) => {
  if (err) throw err;
  console.log('Folder created');
});

This code creates a folder named newFolder.

Read Folder Example:

fs.readdir('.', (err, files) => {
  if (err) throw err;
  console.log(files);
});

This code reads the current folder and prints all file names.

Remove Folder Example:

fs.rmdir('newFolder', (err) => {
  if (err) throw err;
  console.log('Folder removed');
});

This code deletes the folder named newFolder.

Error Handling in Node.js FS

Error control prevents app crashes and helps find issues fast. Always check for err in callbacks or wrap sync calls in try blocks.

Here is an example:

try {
  const data = fs.readFileSync('nofile.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.error('Error occurred:', err.message);
}

This code reads a file and catches errors if the file does not exist.

Examples

Write and Read a File:

fs.writeFile('data.txt', 'Test text', (err) => {
  if (err) throw err;
  fs.readFile('data.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
  });
});

This example first writes text to a file, then reads it back. It shows how two operations can work together without blocking Node.js tasks.

Append and Delete File:

fs.appendFile('data.txt', '\nMore data', (err) => {
  if (err) throw err;
  fs.unlink('data.txt', (err) => {
    if (err) throw err;
    console.log('File removed');
  });
});

This example adds text to a file and then deletes the file. It shows full control over the file life cycle in Node.js.

Work with Directories and Paths:

fs.mkdir('project', (err) => {
  if (err) throw err;
  fs.readdir('.', (err, files) => {
    if (err) throw err;
    console.log(files);
  });
});

This example creates a folder and then lists the current folder’s files. It shows how folder actions link with file reading in Node.js.

Wrapping Up

You learned how Node.js file system works and how its methods work. Here is a quick recap:

  • It can read and write files, handle paths and folders, run sync or async calls, and manage errors with try blocks or callbacks.

FAQs

What is Node.js File System and how does it work?

Node.js File System is a built-in module that allows developers to interact with files. You can read, write, append, and delete files using different methods.
  • readFile() - Reads a file asynchronously.
  • writeFile() - Creates or overwrites a file.
  • appendFile() - Adds content to an existing file.
  • unlink() - Deletes a file.

How do you read and write files in Node.js File System?

To read a file:

const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
To write a file:

const fs = require('fs');
fs.writeFile('example.txt', 'Hello World!', (err) => {
  if (err) throw err;
  console.log('File written successfully!');
});

What is the difference between synchronous and asynchronous methods in Node.js File System?

  • Synchronous Methods: Block execution until file operation completes.
  • Asynchronous Methods: Do not block execution, use callbacks or promises.
Example (Synchronous):

const fs = require('fs');
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
Example (Asynchronous):

const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

How do you delete files using Node.js File System?

You can delete a file with the unlink() method.

const fs = require('fs');
fs.unlink('example.txt', (err) => {
  if (err) throw err;
  console.log('File deleted successfully!');
});

Similar Reads

Node Version Manager (NVM): Manage Node.js Versions

NVM (Node Version Manager ) is a command-line tool used to manage multiple versions of Node.js on a single machine.…

Node.js Streams Guide: How to Handle Data with Examples

Streams pass data in parts, so the app stays fast. This article explains Node.js Streams and how to use them.…

Node JS Buffers Tutorial for Beginners and Pros

Node JS Buffers store raw binary data in memory. This guide shows how to create them, work with them, and…

Node JS Events in Depth with Examples

Node JS runs code in an event-based model and uses events to drive tasks. An event is a signal that…

Node.js REPL: The Complete Tutorial for Beginners

Node.js REPL runs JavaScript code in an instant test space inside your terminal. What is Node.js REPL? Node.js REPL is…

Node.js HTTP Server with Examples for Beginners

This article shows how Node.js creates HTTP servers. It covers requests, responses, routes, HTML, JSON, and gives examples for both…

Node js NPM: How to Publish and Install JS Packages

Node Package Manager (NPM) is an essential tool at the heart of the Node.js ecosystem. This is the defacto package…

Installing Node js on Windows, Ubuntu, and MacOS

Installing node js on Windows, Ubuntu, or macOS. You need to pick the version of Node.js that you want to…

Node.js Hello World: Write Your First Program

In this quick tutorial, you will start Node.js tutorials with a Hello World program. You will learn how to set…

Node.js Modules in Depth with Examples

This guide shows Node.js modules, how they work, how to import and export them, and why you use them. What…

Previous Article

JavaScript with Function Guide: Syntax with Examples

Next Article

PHP array_key_first Function: How it Works with Examples

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.