Sure, here’s a Node.js script that uses the fs
module to rename all the files in a directory to img%d
pattern:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const fs = require('fs'); const path = require('path'); const directoryPath = './my-directory'; // change this to the path of your directory const prefix = 'img'; // change this to the prefix you want to use const extension = '.jpg'; // change this to the file extension you want to use let counter = 1; fs.readdir(directoryPath, (err, files) => { if (err) throw err; files.forEach((file) => { const oldPath = path.join(directoryPath, file); const newPath = path.join(directoryPath, prefix + counter + extension); fs.rename(oldPath, newPath, (err) => { if (err) throw err; console.log(`${oldPath} renamed to ${newPath}`); }); counter++; }); }); |
In this code, the fs.readdir
method is used to read the contents of a directory specified by the directoryPath
variable. The forEach
method is then used to loop through each file in the directory.
For each file, the fs.rename
method is called to rename the file to the img%d
pattern, where %d
is replaced with a counter variable. The counter is incremented after each file is renamed.
The old and new paths of each file are constructed using the path.join
method, which joins the directory path, filename, and extension.
Finally, a console message is printed for each file that is renamed.