How to Mass Rename Files in Node.js
Learn how to easily rename multiple files using Node.js.
In this blog post, I will guide you through the process of renaming a set of files using Node.js.
This process can also be used to move files to another folder, as renaming a file effectively changes its path.
The motivation behind this task was the need to manage blog posts in Hugo. Blog posts can be written as individual files, such as “first-post.md”, “second-post.md”, etc. Alternatively, they can be organized into folders with an “index.md” file, such as “first-post/index.md”, “second-post/index.md”, etc. Using folders allows easier management of associated images for each blog post.
To automate this task, I wanted to rename the files automatically instead of manually changing each one.
Let’s start by requiring the core module ‘fs’. Since it is a core module, there’s no need to install it via npm.
1 | const fs = require('fs'); |
Next, obtain the reference to the current folder. We will assume that the script will be run in the same folder where the file renaming needs to be performed. The variable __dirname
always holds the path to the current working folder.
1 | const files = fs.readdirSync(__dirname); |
Now, we can filter out only the items that have the “.md” extension.
1 | for (const file of files) { |
Once we have the reference to each .md
file, we can use fs.mkdirSync()
to create a new folder.
1 | fs.mkdirSync( |
After creating the folder, we can use fs.renameSync()
to move the file into the newly created folder.
1 | fs.renameSync( |
It’s important to note that I used the blocking versions of mkdirSync()
and renameSync()
instead of their non-blocking counterparts (mkdir()
and rename()
) because I wanted to ensure that the folder is created before moving the file. Using the blocking versions simplifies this process.
Here’s the complete code:
1 | const fs = require('fs'); |
By following these steps, you can easily rename or move a set of files using Node.js. Now you have a quicker and more efficient way of managing your files.
tags: [“Node.js”, “file management”, “file renaming”]