/

How to Mass Rename Files in Node.js

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
2
3
4
5
for (const file of files) {
if (file.endsWith('.md')) {
console.log(file);
}
}

Once we have the reference to each .md file, we can use fs.mkdirSync() to create a new folder.

1
2
3
4
5
6
7
fs.mkdirSync(
__dirname + '/' + file.replace('.md', ''),
{ recursive: true },
(err) => {
console.log(err);
}
);

After creating the folder, we can use fs.renameSync() to move the file into the newly created folder.

1
2
3
4
5
6
7
fs.renameSync(
__dirname + '/' + file,
__dirname + '/' + file.replace('.md', '') + '/index.md',
(err) => {
console.log(err);
}
);

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const fs = require('fs');
const files = fs.readdirSync(__dirname);

for (const file of files) {
if (file.endsWith('.md')) {
fs.mkdirSync(
__dirname + '/' + file.replace('.md', ''),
{ recursive: true },
(err) => {
console.log(err);
}
);

fs.renameSync(
__dirname + '/' + file,
__dirname + '/' + file.replace('.md', '') + '/index.md',
(err) => {
console.log(err);
}
);
}
}

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”]