Mastering File I/O: Read & Write Files in JavaScript (w3schools)

Sarah Jul 13, 2026

Working with files is a fundamental operation in any programming language, including JavaScript. While JavaScript is primarily used for client-side web development, it's equipped with tools to handle files and directories when used on the server side or in a Node.js environment. W3Schools, a popular online learning resource, provides a comprehensive guide on reading and writing files in JavaScript.

JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)
JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)

Let's dive into this topic, starting with the basics of file I/O operations in JavaScript.

Javascript Cheet cheet
Javascript Cheet cheet

Understanding JavaScript's File System Object Model (FSOM)

The File System Object Model (FSOM) in Node.js provides an API for interacting with the host system's file system. It allows you to read, write, create, update, and delete files and directories. To access this module, you simply require it with the following statement:

JavaScript Full Notes Every Beginner Must Save 💡
JavaScript Full Notes Every Beginner Must Save 💡

const fs = require('fs');

Throughout this article, we'll use this 'fs' module to demonstrate reading and writing files in JavaScript.

Synchronous File Operations

an info sheet with different types of web pages
an info sheet with different types of web pages

Synchronous file operations block the execution of your JavaScript program until they complete. They are straightforward to use but can lead to performance issues if not handled correctly.

Here's how you can read a file synchronously:

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

And write to a file synchronously:

Javascript Read Excel
Javascript Read Excel

fs.writeFileSync('filename.txt', 'Hello, World!', 'utf8');

Asynchronous File Operations

Asynchronous file operations allow the execution of your JavaScript program to continue while the file I/O operation completes in the background. This is the recommended approach for better performance and responsiveness.

Here's how you can read a file asynchronously:

Read and write a JSON file in Node.js
Read and write a JSON file in Node.js

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

And write to a file asynchronously:

fs.writeFile('filename.txt', 'Hello, World!', 'utf8', err => {
  if (err) throw err;
  console.log('File saved successfully');
});

Working with Directories

JavaScript | Chapter 2 📖| Part 1 ✨
JavaScript | Chapter 2 📖| Part 1 ✨
JavaScript Template Literals: Write Cleaner & Dynamic Strings 📝
JavaScript Template Literals: Write Cleaner & Dynamic Strings 📝
JavaScript Web Development Cheat Sheet: Your Essential Guide - Connect 4 Programming
JavaScript Web Development Cheat Sheet: Your Essential Guide - Connect 4 Programming
🔥 JavaScript Chapter 1 Notes 2026 📒✨
🔥 JavaScript Chapter 1 Notes 2026 📒✨
JavaScript Literals & Data Types: The Building Blocks of Code 🔢
JavaScript Literals & Data Types: The Building Blocks of Code 🔢
JavaScript Methods: Add Functionality to Your Objects 🚀
JavaScript Methods: Add Functionality to Your Objects 🚀
📘 JavaScript Basics| Linking JS File to HTML | Chapter 2 📖 Part 2
📘 JavaScript Basics| Linking JS File to HTML | Chapter 2 📖 Part 2
Start Writing JavaScript with AI Assistance 🚀
Start Writing JavaScript with AI Assistance 🚀
an open notebook with some type of function written in red on the top and bottom
an open notebook with some type of function written in red on the top and bottom
JavaScript study guide for fast learning
JavaScript study guide for fast learning
Student Management System In JavaScript With Source Code
Student Management System In JavaScript With Source Code
a poster with different types of projects and instructions for students to use in the classroom
a poster with different types of projects and instructions for students to use in the classroom
Examination Apps in JavaScript with Source Code
Examination Apps in JavaScript with Source Code
JavaScript Cheat Sheet You Must Save | Beginner Friendly Guide
JavaScript Cheat Sheet You Must Save | Beginner Friendly Guide
JavaScript Basics | Chapter 1 📖 | Part 2
JavaScript Basics | Chapter 1 📖 | Part 2
JavaScript Reserved Words: What You Need to Know 🚀
JavaScript Reserved Words: What You Need to Know 🚀
javascript cheat sheet web development
javascript cheat sheet web development
JavaScript Fundamental
JavaScript Fundamental
Modern Web Essentials Using JavaScript and HTML5
Modern Web Essentials Using JavaScript and HTML5
JavaScript Works in the Browser
JavaScript Works in the Browser

In addition to files, you can also perform operations on directories (folders) using the FSOM.

Here's how you can create a new directory:

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

Reading Directory Contents

You can read the contents of a directory using the 'readdir' method. This method returns an array of files and directories in the specified path.

Here's how it works:

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

Deleting Files and Directories

To delete a file or directory, you can use the 'unlink' or 'rmdir' methods respectively. However, deleting a directory that contains files or subdirectories requires the 'rm' method.

Deleting files and directories is an asynchronous operation, so you'll need to handle the potential error using a callback function or promises.

Here's where you should take a break and practice these file I/O operations in your local environment. Try creating, reading, and deleting files and directories using both synchronous and asynchronous methods.

Error Handling in File Operations

File I/O operations in JavaScript can throw errors for various reasons, such as file not found, insufficient permissions, or network issues. It's essential to handle these errors to prevent your application from crashing.

In the examples above, we used callback functions to handle potential errors. However, you can also use promises or async/await syntax for more modern and readable error handling.

Promises with File Operations

The 'fs' module provides promise-based alternatives to most of its methods. These promises are returned when you call the methods with the 'promise' callback, like so:

fs.promises.readFile('filename.txt', 'utf8')
  .then(data => console.log(data))
  .catch(err => console.error(err));

Async/Await with File Operations

Async/await syntax allows you to write asynchronous code that looks like synchronous (sequential) code. To use async/await with file operations, you'll need to define a function with the 'async' keyword and use the 'await' keyword before calling the promise-based methods.

async function readFile() {
  try {
    const data = await fs.promises.readFile('filename.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

Async/await is a more modern and readable approach to handling asynchronous code, making it easier to reason about your application's flow and potential errors.

As you continue learning and refining your skills, remember to always test your code in various scenarios and edge cases to ensure it behaves as expected. Good luck on your JavaScript journey, and happy coding!