Node.js / Node.js File System

Performing File and Directory Operations

This tutorial will teach you how to perform file and directory operations in Node.js. We'll delve into creating, reading, updating, and deleting files and directories using the fs…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers working with the file system to read, write, and manipulate files in Node.js.

Performing File and Directory Operations in Node.js

1. Introduction

In this tutorial, we're going to explore how to perform file and directory operations in Node.js. You will learn how to create, read, update, and delete files and directories using the built-in fs (file system) module in Node.js.

By the end of this tutorial, you should be able to:

  • Understand how to manipulate files and directories in Node.js
  • Apply these operations in your web development projects

Prerequisites: Basic knowledge of JavaScript and Node.js is required. You should also have Node.js installed on your system.

2. Step-by-Step Guide

Node.js fs module provides an API to interact with the file system in a manner closely modeled around standard POSIX functions.

To use this module, you need to require it in your script:

const fs = require('fs');

Creating a New File

To create a new file in Node.js, you can use the fs.writeFile() method:

fs.writeFile('test.txt', 'Hello, World!', (err) => {
  if (err) throw err;
  console.log('File has been created');
});

Reading a File

To read a file in Node.js, you can use the fs.readFile() method:

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

3. Code Examples

Let's put everything together and create a more complex example:

// Include fs module
const fs = require('fs');

// Use fs.writeFile() method to create a new file
fs.writeFile('test.txt', 'Hello, World!', (err) => {
  if (err) throw err;

  console.log('File has been created');

  // Use fs.readFile() method to read the file
  fs.readFile('test.txt', 'utf8', (err, data) => {
    if (err) throw err;

    console.log(data);
  });
});

In this code snippet:

  1. We first include the fs module.
  2. We use fs.writeFile() to create a new file 'test.txt' and write 'Hello, World!' to it. If the file already exists, it will be overwritten.
  3. In the callback function of fs.writeFile(), we use fs.readFile() to read the file we just created. The content of the file will be printed to the console.

4. Summary

In this tutorial, we've covered the basics of performing file and directory operations in Node.js. We've learned how to create a new file and how to read a file using the fs module. The next step would be to explore other methods provided by the fs module, such as fs.appendFile(), fs.unlink(), and fs.mkdir().

5. Practice Exercises

  1. Write a script to append text to an existing file.
  2. Write a script to delete a file.
  3. Write a script to create a new directory.

Exercise 1 Solution:

fs.appendFile('test.txt', ' This is a test.', (err) => {
  if (err) throw err;
  console.log('Text has been appended');
});

Exercise 2 Solution:

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

Exercise 3 Solution:

fs.mkdir('testDir', (err) => {
  if (err) throw err;
  console.log('Directory has been created');
});

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help