Node.js / Node.js File System

Reading and Writing Files in Node.js

This tutorial will guide you through the process of reading and writing files in Node.js. You'll learn how to open, read, write, and close files using the fs module provided by No…

Tutorial 1 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.

Reading and Writing Files in Node.js

1. Introduction

This tutorial aims to provide a step-by-step guide to reading and writing files in Node.js. We'll use the built-in fs (file system) module in Node.js to open, read, write, and close files.

By the end of this tutorial, you'll learn:

  • How to include the fs module in your Node.js application
  • How to read files using the fs module
  • How to write to files using the fs module

Prerequisites: Basic understanding of JavaScript and Node.js.

2. Step-by-Step Guide

The fs module in Node.js is designed to work with the file system on your computer. It allows you to work with files on your server, including creating, reading, updating, deleting, and renaming files.

Including the fs Module

To use the fs module, you need to require it in your application:

const fs = require('fs');

Reading Files

To read the content of a file, use the fs.readFile() function. This function reads the entire file and then calls the callback function with the file content:

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

Writing Files

To write to a file, use the fs.writeFile() function. If the file does not exist, it will be created:

fs.writeFile('example.txt', 'Hello, World!', function(err) {
  if (err) throw err;
  console.log('File written!');
});

3. Code Examples

Reading a File

const fs = require('fs');

// Read the file
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('An error occurred:', err);
    return;
  }
  // The file data is a string
  console.log('File content:', data);
});

In this code snippet, we read the file example.txt and then log its contents to the console. If an error occurs (for example, if the file does not exist), we log the error message.

Writing a File

const fs = require('fs');

// Write to the file
fs.writeFile('example.txt', 'Hello, World!', (err) => {
  if (err) {
    console.error('An error occurred:', err);
    return;
  }
  console.log('File written successfully!');
});

In this code snippet, we write the string Hello, World! to the file example.txt. If the file does not exist, it will be created. If an error occurs, we log the error message.

4. Summary

In this tutorial, we learned how to read and write files in Node.js using the fs module. We've covered how to include the fs module in your application and use its readFile() and writeFile() functions to interact with files.

For further learning, explore other fs functions, such as fs.appendFile() to append data to a file, fs.rename() to rename a file, and fs.unlink() to delete a file.

5. Practice Exercises

  1. Write a Node.js script to create a new text file and write the string "I'm learning Node.js!" to it.
  2. Write a Node.js script to read the file created in the previous exercise and log its contents to the console.
  3. Modify the script from exercise 2 to append "And it's fun!" to the file before reading it.

Remember, practice is key to mastering any programming concept. Happy coding!

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

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

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