Working with folders in Node.js
The Node.js fs core module provides many handy methods you can use to work with folders.
Check if a folder exists
Use fs.access() (and its promise-based fsPromises.access() counterpart) to check if the folder exists and Node.js can access it with its permissions.
Create a new folder
Use fs.mkdir() or fs.mkdirSync() or fsPromises.mkdir() to create a new folder.
const = ('node:fs');
const = '/Users/joe/test';
try {
if (!.()) {
.();
}
} catch () {
.();
}
Read the content of a directory
Use fs.readdir() or fs.readdirSync() or fsPromises.readdir() to read the contents of a directory.
This piece of code reads the content of a folder, both files and subfolders, and returns their relative path:
const = ('node:fs');
const = '/Users/joe';
.();
You can get the full path:
fs.readdirSync(folderPath).map( => {
return path.join(folderPath, );
});
You can also filter the results to only return the files, and exclude the folders:
const = ('node:fs');
const = => {
return .().();
};
.(folderPath)
.( => {
return path.join(folderPath, );
})
.();
Rename a folder
Use fs.rename() or fs.renameSync() or fsPromises.rename() to rename folder. The first parameter is the current path, the second the new path:
const = ('node:fs');
.('/Users/joe', '/Users/roger', => {
if () {
.();
}
// done
});
fs.renameSync() is the synchronous version:
const = ('node:fs');
try {
.('/Users/joe', '/Users/roger');
} catch () {
.();
}
fsPromises.rename() is the promise-based version:
const = ('node:fs/promises');
async function () {
try {
await .('/Users/joe', '/Users/roger');
} catch () {
.();
}
}
();
Remove a folder
Use fs.rmdir() or fs.rmdirSync() or fsPromises.rmdir() to remove a folder.
const = ('node:fs');
.(dir, => {
if () {
throw ;
}
.(`${dir} is deleted!`);
});
To remove a folder that has contents use fs.rm() with the option { recursive: true } to recursively remove the contents.
{ recursive: true, force: true } makes it so that exceptions will be ignored if the folder does not exist.
const = ('node:fs');
.(dir, { : true, : true }, => {
if () {
throw ;
}
.(`${dir} is deleted!`);
});