Working with the File System in JavaScript (Node.js): A Complete Guide for Beginners
Working with the file system is one of the key tasks when creating server applications, automation scripts, or data processing utilities. In JavaScript (Node.js), there is a built-in module fs (File System) for this purpose. This article will introduce you to the basics of working with files and folders in Node.js, show you how to read, write, create, and delete files, and explain the difference between synchronous and asynchronous methods.
What is the fs module in Node.js?
The fs module provides an API for interacting with the operating system's file system. It allows you to perform operations such as:
- Reading file contents
- Writing data to files
- Creating and deleting directories
- Renaming and copying files
- Checking file existence
- Getting file information (statistics)
To start using the fs module, you need to include it in your code:
const fs = require('fs');All methods of the fs module are available in three variants: synchronous (with the Sync suffix), asynchronous with callbacks, and promise-based asynchronous (using fs.promises). In this guide, we will focus on the modern approach using async/await.
Reading Files in Node.js
The simplest way to read a file's contents is to use the readFile method from fs.promises. Let's look at an example:
const fs = require('fs').promises;
async function readFileExample() { try { const data = await fs.readFile('example.txt', 'utf8'); console.log('File contents:', data); } catch (error) { console.error('Error reading file:', error.message); }}
readFileExample();In this example:
- We import
fs.promises— the version of the module that returns promises. - The
readFilefunction takes the file path and encoding (in this case'utf8'). - If the file does not exist, an error will be thrown, which we handle in the
catchblock.
If you need to read a file synchronously (in simple scripts), use readFileSync:
const fs = require('fs');
try { const data = fs.readFileSync('example.txt', 'utf8'); console.log(data);} catch (error) { console.error(error.message);}Important: Synchronous methods block code execution until the operation completes. In server applications (e.g., on Express), always use asynchronous methods to avoid blocking the processing of other requests.
Writing Data to Files
To write data to a file, use the writeFile method. If the file exists, its contents will be overwritten. If the file does not exist, it will be created automatically.
const fs = require('fs').promises;
async function writeFileExample() { try { const content = 'Hello, world! This is a test entry.'; await fs.writeFile('output.txt', content, 'utf8'); console.log('File successfully written!'); } catch (error) { console.error('Write error:', error.message); }}
writeFileExample();If you want to add data to the end of an existing file (without overwriting it), use the appendFile flag:
const fs = require('fs').promises;
async function appendToFile() { try { await fs.appendFile('log.txt', `New entry: ${new Date()}`, 'utf8'); console.log('Data appended to the end of the file'); } catch (error) { console.error('Error:', error.message);\