Facebook Pixel
Step-by-Step Guide

How to Work with the Node.js File System Module

A step-by-step guide on how to read, write, update, delete, and stream files using the Node.js fs module.

Import the fs Module

The fs module is built into Node.js and requires no installation. Import it using require('fs') for the callback-based API, require('fs').promises for the Promise-based API, or import the promises namespace directly. For modern Node.js applications, prefer the Promise-based API with async await, which avoids callback nesting and integrates cleanly with the rest of your async code.

Read Files Asynchronously

Use fs.promises.readFile with the file path and an encoding argument of 'utf8' to read the entire contents of a file as a string. Await the result inside an async function. If you omit the encoding, the function returns a Buffer of raw bytes instead of a string. Always wrap file operations in try-catch to handle cases where the file does not exist or permissions are denied.

Write Files Asynchronously

Use fs.promises.writeFile with the file path and the data you want to write. If the file does not exist, it is created automatically. If it does exist, its entire contents are replaced. To add content to the end of an existing file without overwriting it, use fs.promises.appendFile instead. Both functions accept strings, Buffers, or TypedArrays as data.

Check if a File Exists

Use fs.promises.access with the file path and fs.constants.F_OK to check if a file exists and is accessible. Wrap it in a try-catch. If the file exists and is accessible, access resolves without a value. If the file does not exist or cannot be accessed, it rejects with an error. Avoid the deprecated fs.exists method as it does not follow the standard Node.js error-first callback convention.

Read Directory Contents

Use fs.promises.readdir with a directory path to get an array of file and directory names inside that directory. Pass the option withFileTypes: true to receive Dirent objects instead of strings. Dirent objects have methods like isFile and isDirectory that let you distinguish between files and subdirectories without making additional filesystem calls.

Create and Delete Directories

Use fs.promises.mkdir to create a directory. Pass the option recursive: true to create all intermediate directories that do not yet exist, similar to mkdir -p in Unix. To delete a directory, use fs.promises.rm with the options recursive: true and force: true to remove it along with all its contents. These options make the operation behave like rm -rf in Unix.

Watch Files for Changes

Use fs.watch with a file or directory path to receive notifications whenever that file or directory changes. It accepts a callback that receives the event type, which is either rename or change, and the filename. The watcher returns an object with a close method you must call to stop watching. Use this for building development tools, configuration hot-reloading, or file synchronization utilities.

Use Streams for Large Files

For files larger than a few megabytes, reading the entire file into memory at once with readFile is inefficient and can crash your server with out-of-memory errors. Use fs.createReadStream to read the file in small chunks as a readable stream. Use fs.createWriteStream to write data incrementally. Pipe a readable stream to a writable stream to transfer data with automatic backpressure management.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.