- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js Working with Folders
In any backend application, managing the file system is a fundamental task. Node.js provides the built-in fs (File System) module, which acts as a powerful toolkit for interacting with directories. Whether you are building a system to organize user-uploaded images, generating automated reports, or managing temporary log files, understanding how to programmatically create, read, and delete folders is essential.
fs module is standard, always pair it with the path module. Using path.join() ensures your folder paths work correctly on both Windows (which uses backslashes \) and Linux/macOS (which use forward slashes /).
Key Features of Working with Folders
- Creating Directories: You can generate new folders on the fly. This is particularly useful for organizing data by date or user ID.
- Reading Directories: This allows you to "scan" a folder to see what files or sub-folders exist inside it, similar to opening a folder in your OS file explorer.
- Removing Directories: You can clean up your workspace by removing empty or non-empty directories when they are no longer needed.
- Directory Information: Before performing an action, you can check if a folder exists or retrieve its metadata (like creation date).
Creating Directories
1. fs.mkdir()
The fs.mkdir() (make directory) method is asynchronous. It tells Node.js to start creating a folder and move on to the next line of code immediately. Once the folder is actually created, a callback function runs to handle the result.
const fs = require('fs');
fs.mkdir('logs', (err) => {
if (err) {
return console.error('Could not create directory:', err.message);
}
console.log('Directory created successfully!');
});
Output:
Directory created successfully!
{ recursive: true } option. If you try to create ./uploads/2024/images and the uploads folder doesn't exist yet, mkdir will fail. Setting recursive: true tells Node to create all parent folders automatically.
2. fs.mkdirSync()
The fs.mkdirSync() method is the synchronous version. This "blocks" the execution of your code; the script stops and waits until the folder is created before moving to the next line.
const fs = require('fs');
try {
fs.mkdirSync('backups');
console.log('Backup directory created');
} catch (err) {
console.error('Error creating folder:', err);
}
Output:
Backup directory created
mkdirSync can slow down high-traffic web servers because they stop the entire event loop. Use them mainly for simple CLI scripts or during the initial startup phase of your application.
Reading Directories
1. fs.readdir()
The fs.readdir() method scans a directory and returns an array containing the names of all files and folders found inside it.
const fs = require('fs');
fs.readdir('./my_project', (err, files) => {
if (err) throw err;
console.log('Contents:', files);
});
Output:
Contents: [ 'index.js', 'package.json', 'node_modules', 'public' ]
fs.readdir only returns the names of the files, not the full paths. To do something with those files (like delete them), you must manually join the directory path with the filename.
2. fs.readdirSync()
This is useful when you need to get a list of files immediately before proceeding with your logic, such as loading all configuration files from a folder at startup.
const fs = require('fs');
const items = fs.readdirSync('.');
items.forEach(item => {
console.log('Found item:', item);
});
Removing Directories
1. fs.rmdir()
The fs.rmdir() method is specifically designed to remove a directory. By default, in older versions of Node.js, this method only works if the directory is empty.
const fs = require('fs');
fs.rmdir('temp_logs', (err) => {
if (err) throw err;
console.log('Empty directory removed');
});
fs.rmdir() is being phased out for non-empty directories. For modern applications, it is recommended to use fs.rm() with the recursive and force options.
2. fs.rmdirSync()
The synchronous version of folder removal. Like its counterpart, it will throw an error if the directory does not exist or if it contains files (unless specific flags are used).
const fs = require('fs');
fs.rmdirSync('old_data');
console.log('Directory removed');
3. fs.rmdir() for Non-Empty Directories
In older Node.js scripts, you had to manually delete every file inside a folder before you could delete the folder itself. Here is a practical look at how that logic functions:
const fs = require('fs');
const path = require('path');
function cleanAndRemove(dirPath) {
if (fs.existsSync(dirPath)) {
// Read all files in the directory
fs.readdir(dirPath, (err, files) => {
if (err) throw err;
files.forEach((file) => {
const currentPath = path.join(dirPath, file);
// Remove individual file
fs.unlink(currentPath, (err) => {
if (err) throw err;
});
});
// Finally, remove the now-empty directory
fs.rmdir(dirPath, (err) => {
if (err) throw err;
console.log('Folder cleared and deleted.');
});
});
}
}
cleanAndRemove('temp_uploads');
fs.rm('folder_name', { recursive: true, force: true }, callback). This handles non-empty folders and missing folders in a single, clean line of code.
Checking if a Directory Exists
1. fs.existsSync()
Before trying to create or read a folder, it’s often smart to check if it actually exists to avoid crashing your app with an error.
const fs = require('fs');
const dir = './data_store';
if (fs.existsSync(dir)) {
console.log('Folder found! Proceeding with data load...');
} else {
console.log('Folder not found. Creating it now...');
fs.mkdirSync(dir);
}
Output:
Folder not found. Creating it now...
Summary
Mastering the fs module allows you to build Node.js applications that are organized and capable of handling complex file-based data. By using fs.mkdir() to create structures, fs.readdir() to inspect them, and fs.rm() to clean them up, you gain full control over the local environment. Always remember to use asynchronous methods for performance-critical applications and leverage the path module to keep your code compatible across different operating systems.