Incrementing Multiple Folders Numbers at Once Using Node.js
How I Solved a Folder Management Problem
Recently, I encountered a problem while creating a large number of folders. Each folder was formatted with a number followed by a dash and a string, like this:
1 | 1-yo |
Later, I realized that I needed to insert a new folder in the middle, like this:
1 | 1-yo |
The challenge arose when I had to change the numbers of all subsequent folders to reflect the insertion of the 3-NEWONE
folder. To automate this process and avoid manual effort in the future, I decided to create a Node.js command line app called increment.js
.
To start, I added a command line argument to specify the number from which I wanted the folders to be incremented. For example:
1 | node rename.js 4 |
To retrieve the command line argument in Node.js, I used process.argv
:
1 | const args = process.argv.slice(2); |
If no number is provided as an argument, the program will display an error message and terminate:
1 | if (!startingNumber) { |
Now that I had the starting number, the next step was to retrieve the names of the folders that needed to be incremented. Since the script was placed in the same folder as the subfolders, I could simply read from ./
, which refers to the current folder. Here’s how I retrieved the names of all files and subfolders in the current folder:
1 | const fs = require('fs'); |
To ensure that only folders were retrieved, I added a filter to exclude files.
Next, I iterated through the list of folders:
1 | folders.map((folder) => { |
Within the iteration, I extracted the number from each folder name:
1 | folders.map((folder) => { |
If there was a match (indicating that the folder had a number in its name), I extracted the number and converted it from a string to a number:
1 | folders.map((folder) => { |
Finally, if the extracted number was higher than or equal to the starting number argument, I renamed the folder by incrementing the number:
1 | folders.map((folder) => { |
And that’s it! The above code represents the final source code of the CLI app.
1 | const fs = require('fs'); |
Tags: node.js, folder management, command line app, automation