Working with folders in Node
By Flavio Copes
Learn how to work with folders in Node.js using the fs module to check, create, read, rename, and remove directories with fs.rm.
The Node.js fs module provides many handy methods you can use to work with folders.
Check if a folder exists
Use fs.access() to check if the folder exists and Node can access it with its permissions.
Create a new folder
Use fs.mkdir() or fs.mkdirSync() to create a new folder.
const fs = require('fs')
const folderName = '/Users/flavio/test'
try {
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName)
}
} catch (err) {
console.error(err)
}
With ESM and the node: prefix:
import fs from 'node:fs'
const folderName = '/Users/flavio/test'
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName)
}
Read the content of a directory
Use fs.readdir() or fs.readdirSync 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 fs = require('fs')
const path = require('path')
const folderPath = '/Users/flavio'
fs.readdirSync(folderPath)
You can get the full path:
fs.readdirSync(folderPath).map(fileName => {
return path.join(folderPath, fileName)
}
You can also filter the results to only return the files, and exclude the folders:
const isFile = fileName => {
return fs.lstatSync(fileName).isFile()
}
fs.readdirSync(folderPath).map(fileName => {
return path.join(folderPath, fileName)
}).filter(isFile)
Rename a folder
Use fs.rename() or fs.renameSync() to rename folder. The first parameter is the current path, the second the new path:
const fs = require('fs')
fs.rename('/Users/flavio', '/Users/roger', err => {
if (err) {
console.error(err)
return
}
//done
})
fs.renameSync() is the synchronous version:
const fs = require('fs')
try {
fs.renameSync('/Users/flavio', '/Users/roger')
} catch (err) {
console.error(err)
}
Remove a folder
Use fs.rm() or fs.rmSync() to remove a folder.
For a folder that still has files inside, pass { recursive: true, force: true }. That is the built-in way to delete a tree, available since Node 14.14. You do not need a third-party package for this.
Be careful with the path: this deletes everything inside it, with no confirmation.
const fs = require('fs')
const folder = '/Users/flavio/test'
fs.rmSync(folder, { recursive: true, force: true })
The async callback form:
fs.rm(folder, { recursive: true, force: true }, err => {
if (err) {
console.error(err)
return
}
//done
})
Or with fs/promises:
import { rm } from 'node:fs/promises'
const folder = '/Users/flavio/test'
await rm(folder, { recursive: true, force: true })
fs.rmdir() / fs.rmdirSync() still exist for empty directories, but for recursive deletes prefer fs.rm().
If you already use fs-extra, its remove() helper works too. For new code, stick to the built-in fs.rm().
Want me to talk about your product? You can sponsor this site.
Related posts about node: