Working with folders in Node: A Guide
Learn how to interact with folders using Node.js and the fs
core module. Discover methods for checking if a folder exists, creating a new folder, reading the content of a directory, renaming a folder, and removing a folder.
Check if a folder exists
To check if a folder exists and if Node.js has access to it, use the fs.access()
method.
1 | const fs = require('fs'); |
Create a new folder
To create a new folder, use either the fs.mkdir()
or fs.mkdirSync()
method.
1 | const fs = require('fs'); |
Read the content of a directory
To read the contents of a directory, including files and subfolders, use either the fs.readdir()
or fs.readdirSync()
method.
This code reads the content of a folder and returns the relative path of each file and subfolder.
1 | const fs = require('fs'); |
To get the full path of each file and subfolder, use path.join()
.
1 | const content = fs.readdirSync(folderPath).map(fileName => { |
To filter the results and only return files (excluding folders), you can use the isFile()
method provided by the fs
module.
1 | const isFile = fileName => { |
Rename a folder
To rename a folder, use either the fs.rename()
or fs.renameSync()
method. Pass the current path as the first parameter and the new path as the second parameter.
1 | const fs = require('fs'); |
The fs.renameSync()
method can be used for synchronous renaming.
1 | try { |
Remove a folder
To remove a folder, use either the fs.rmdir()
or fs.rmdirSync()
method.
1 | const fs = require('fs'); |
Please note that removing a folder with content can be more complicated. If you need advanced features, it is recommended to use the popular and well-maintained fs-extra
module. The remove()
method from fs-extra
provides additional functionality on top of the fs
module.
To use fs-extra
, install it via NPM:
1 | npm install fs-extra |
Then, you can remove a folder using fs.remove()
.
1 | const fs = require('fs-extra'); |
Alternatively, you can use promises or async/await with fs-extra
.
1 | fs.remove(folderPath) |
1 | async function removeFolder(folderPath) { |
tags: [“Node.js”, “folders”, “file system”, “fs module”]