Back to JavaScript
2026-01-036 min read

File system API (JavaScript)

Learn File system API (JavaScript) step by step with clear examples and exercises.

Why This Matters

The File System API in JavaScript is a crucial tool for modern web development, enabling developers to interact with files on users' local devices or network file systems securely and efficiently. By understanding this API, you can create more versatile web applications that save user data, read configuration files, or even build customizable interfaces.

Prerequisites

To follow along with this lesson, you should have a good understanding of:

  • JavaScript basics, including variables, functions, and control structures
  • Asynchronous programming concepts using Promises or async/await
  • Familiarity with HTML and the Document Object Model (DOM)
  • Node.js and its package manager npm (for running Node.js scripts in a browser environment)

Installing Node.js and npm

To use the File System API, you'll need to have Node.js and npm installed on your machine. You can download Node.js from the official website and npm will be installed automatically.

Setting up a local development server

For running JavaScript files with the File System API in a browser environment, you'll need to set up a local development server. One popular choice is LiveServer for Visual Studio Code.

Core Concept

Introduction

The File System API allows you to interact with files on a user's local device or network file system using JavaScript. It provides core functionality such as reading, writing, and managing files.

// Importing the FileSystem API
const fs = require('fs');

Reading Files

To read a file using the File System API, you can use the readFile() method. This method takes three arguments: the file path, an encoding option (e.g., 'utf8'), and a callback function that will be executed when the file is read.

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

Reading Files with Promises

For easier handling and chaining of asynchronous operations, you can use Promises instead of callbacks:

const { promises: fsPromises } = require('fs');

// Reading a file using Promises
async function readFilePromise(filePath) {
try {
const data = await fsPromises.readFile(filePath, 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}

Writing Files

Writing to a file can be done using the writeFile() method. This method takes four arguments: the file path, the content to write, an encoding option (e.g., 'utf8'), and an options object that specifies mode (e.g., 'w' for writing over existing files).

// Writing to a file
fs.writeFile('example.txt', 'Hello World!', { flag: 'wx' }, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});

Writing Files with Promises

For writing files using Promises, you can use the following approach:

// Writing to a file using Promises
async function writeFilePromise(filePath, content) {
try {
await fsPromises.writeFile(filePath, content, 'utf8');
console.log('The file has been saved!');
} catch (err) {
console.error(err);
}
}

Directory Operations

You can also perform operations on directories using the File System API. For example, to read the contents of a directory, you can use the readdir() method.

// Reading the contents of a directory
fs.readdir('./', (err, files) => {
if (err) throw err;
console.log(files);
});

Reading Directory Contents with Promises

For reading directory contents using Promises:

// Reading the contents of a directory using Promises
async function readDirectoryPromise(directoryPath) {
try {
const files = await fsPromises.readdir(directoryPath);
console.log(files);
} catch (err) {
console.error(err);
}
}

File Streams

The File System API also supports file streams using createReadStream(), createWriteStream(), and other related methods for reading and writing files in a stream-like manner. This can be useful when dealing with large files or performing operations like concatenating multiple files.

Worked Example

Let's create a simple text editor using the File System API. This application will allow users to create, read, and save text files on their local device.

Creating the Application Structure

First, create an HTML file with a basic structure for your text editor:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Simple Text Editor</title>
</head>
<body>
<textarea id="editor"></textarea>
<button onclick="saveFile()">Save File</button>
<script src="app.js"></script>
</body>
</html>

Next, create a JavaScript file (app.js) to handle the functionality:

// Importing the FileSystem API with Promises
const { promises: fsPromises } = require('fs');

// Initializing the text editor
const editor = document.getElementById('editor');
let filePath = './example.txt';

async function readFile() {
try {
const data = await fsPromises.readFile(filePath, 'utf8');
editor.value = data;
} catch (err) {
console.error(err);
}
}

function saveFile() {
const content = editor.value;
fsPromises.writeFile(filePath, content, 'utf8')
.then(() => console.log('The file has been saved!'))
.catch((err) => console.error(err));
}

// Loading the file on page load
readFile();

Common Mistakes

1. Forgetting to handle errors

Always include error handling in your File System API code to prevent potential issues and ensure a smoother user experience.

2. Not specifying the file encoding

When reading or writing files, always specify the encoding (e.g., 'utf8') to avoid unexpected characters and errors.

3. Misusing the file path

Ensure that the provided file path is correct and accessible by the application. Relative paths should be relative to the script's location, while absolute paths should point directly to the desired file.

4. Not closing file streams properly

Always close file streams when they are no longer needed to free up system resources. This can be done using the end() method for write streams and the destroy() method for read streams.

5. Using callbacks instead of Promises for asynchronous operations

While callbacks work, using Promises makes handling and chaining asynchronous operations easier and more manageable.

Practice Questions

  1. Write a JavaScript function to delete a file using the File System API.
  2. Modify the Simple Text Editor example to allow users to create new files instead of overwriting existing ones.
  3. Implement a functionality to rename a file using the File System API in the Simple Text Editor example.
  4. Write a script that concatenates multiple text files into one using the File System API and file streams.
  5. How can you handle situations where a user tries to write to a read-only file or directory using the File System API?

FAQ

1. What is the difference between 'w' and 'wx' modes when writing files with fs.writeFile()?

The 'w' mode will overwrite an existing file, while 'wx' will create a new file only if it does not already exist.

2. How can I read binary files using the File System API in JavaScript?

To read binary files, you should pass 'binary' as the encoding option when using the readFile() method:

fs.readFile('./example.bin', 'binary', (err, data) => {
// Handle the binary data here
});

3. Can I use the File System API to interact with remote files on a network?

No, the File System API is designed for local file system interactions only and does not support remote file access. For remote file interactions, you can use APIs like Fetch or XMLHttpRequest.

4. How can I handle situations where a user tries to write to a read-only file or directory using the File System API?

To handle read-only files or directories, you can check the fs.constants object for error codes such as 'EACCES' (permission denied) and provide appropriate feedback to the user. You may also want to consider providing an option for users to temporarily make the file writable before saving their data and then making it read-only again.

writerStream.on('error', err => {
if (err.code === 'EACCES') {
alert('You do not have permission to write to this file or directory.');
return;
}
throw err;
});
File system API (JavaScript) | JavaScript | XQA Learn