Working with the File System in Node.js: A Complete Guide

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

Working with the File System in Node.js: A Complete Guide



In modern web development, the ability to efficiently work with the file system is one of the key skills for a backend developer. Node.js provides a powerful and flexible fs (File System) module that allows you to perform all basic operations with files and directories: reading, writing, deleting, renaming, and much more. In this article, we will thoroughly examine how to work with the file system in Node.js, look at synchronous and asynchronous methods, and also study working with paths.



Importing the fs Module and Basic Principles



To start working with the file system in Node.js, you need to import the built-in fs module. This is done with one line of code:



const fs = require('fs');


The fs module provides both synchronous and asynchronous methods. Asynchronous methods typically accept a callback function as the last argument and are preferred for production code, as they do not block the event loop. Synchronous methods end with Sync and can be useful during application initialization or in scripts.



Additionally, starting from Node.js 10, working with fs/promises is available — a version of the methods that return promises:



const fs = require('fs/promises');


In this article, we will primarily use the asynchronous approach with promises, as it is the most modern and convenient.



Reading Files in Node.js



Reading files is one of the most common operations. Let's look at three main methods.



Reading an Entire File at Once (Asynchronously)



The fs.readFile() method reads the entire file content into memory. This is convenient for small files.



const fs = require('fs/promises');

async function readFileExample() { try { const data = await fs.readFile('example.txt', 'utf8'); console.log('File content:', data); } catch (err) { console.error('Error reading file:', err); }}

readFileExample();


Reading a File Line by Line (Streaming)



For large files, it is better to use streams or read the file line by line using readline:



const fs = require('fs');const readline = require('readline');

async function readFileLineByLine() { const fileStream = fs.createReadStream('large-file.txt'); const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });

for await (const line of rl) { console.log('Line:', line); }}

readFileLineByLine();


Synchronous Reading



If you need to read a file right now and are willing to block execution:



const fs = require('fs');

try { const data = fs.readFileSync('example.txt', 'utf8'); console.log(data);} catch (err) { console.error(err);}


Writing and Updating Files



Node.js provides several methods for writing data to files.



Writing to a File (Overwriting)



The fs.writeFile() method creates a new file or overwrites an existing one:



const fs = require('fs/promises');

async function writeFileExample() { try { await fs.writeFile('output.txt', 'Hello, world!', 'utf8'); console.log('File successfully written'); } catch (err) { console.error('Write error:', err); }}

writeFileExample();


Appending Data to the End of a File



If you need to add data without deleting existing content, use fs.appendFile():



const fs = require('fs/promises');

async function appendToFile() { try { await fs.appendFile('log.txt', `New entry: ${new Date()}`); console.log('Data appended'); } catch (err) { console.error('Error:', err); }

Blogs

Book Recommendations