Working with the File System in JavaScript: A Practical Guide for Node.js

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why Learn to Work with Files in JavaScript?

\n\n

When we talk about JavaScript, most people immediately think of the browser and interactive interfaces. However, with the advent of the Node.js platform, JavaScript has gone far beyond web pages. Today it is a full-fledged language for server-side development, automation, and utilities. And one of the key tasks every developer faces is working with the file system.

\n\n

The ability to read, write, move, and delete files is a fundamental skill without which no serious project can be imagined. Whether it's a logger, a configuration file, image uploads, or data analysis — access to the file system is needed everywhere.

\n\n

In this article, we will cover practical examples of working with the file system in Node.js. You will learn how to use the built-in fs module, what methods are available, and how to avoid common mistakes. All the code can be run and tested immediately.

\n\n

Basic Methods of the fs Module

\n\n

The fs (File System) module is included in the standard Node.js distribution. It does not need to be installed separately. To get started, simply require it at the beginning of your file:

\n\n
const fs = require('fs');\nconst fsPromises = require('fs').promises; // for working with promises
\n\n

All methods of the fs module exist in three variants:

\n\n
    \n
  • Synchronous — block code execution until the operation completes. Usually have the Sync suffix.
  • \n
  • Asynchronous with callbacks — the classic Node.js style.
  • \n
  • Asynchronous with promises — a modern approach using fs.promises.
  • \n
\n\n

In modern projects, it is recommended to use promises and async/await. This makes the code cleaner and more understandable.

\n\n

Reading Files

\n\n

The most common scenario is reading the contents of a file. Let's look at an example with a text file data.txt:

\n\n
const fs = require('fs').promises;\n\nasync function readFileExample() {\n    try {\n        const data = await fs.readFile('data.txt', 'utf8');\n        console.log('File contents:');\n        console.log(data);\n    } catch (err) {\n        console.error('Error reading file:', err.message);\n    }\n}\n\nreadFileExample();
\n\n

The second parameter 'utf8' specifies the encoding. If you omit it, you will get a raw buffer. For text files, always specify the encoding.

\n\n

Writing to a File

\n\n

Writing data to a file can be done in two ways: complete overwrite or appending to the end.

\n\n

Overwriting a file:

\n
const fs = require('fs').promises;\n\nasync function writeFileExample() {\n    try {\n        await fs.writeFile('output.txt', 'Hello, file system!');\n        console.log('File successfully written');\n    } catch (err) {\n        console.error('Error writing:', err.message);\n    }\n}\n\nwriteFileExample();
\n\n

Appending to the end of a file:

\n
const fs = require('fs').promises;\n\nasync function appendFileExample() {\n    try {\n        await fs.appendFile('log.txt', `New entry: ${new Date().toISOString()}\\n`);\n        console.log('Data appended');\n    } catch (err) {\n        console.error('Error appending:', err.message);\n    }\n}\n\nappendFileExample();
\n\n

The appendFile method is ideal for logging or accumulating data.

\n\n

Managing Directories and Files

\n\n

Working with the file system is not limited to reading and writing. Often you need to create folders, check if files exist, or delete them.

\n\n

Creating and Deleting Directories

\n\n
const fs = require('fs').promises;\n\nasync function manageDirectories() {\n    try {\n        // Creating a directory (if it doesn't exist)\n        await fs.mk                

Blogs

Book Recommendations