EN
Node.js - rename multiple files
0 points
In this article, we would like to show you how to rename multiple files in Node.js.
Quick solution:
xxxxxxxxxx
1
const fs = require('fs');
2
β
3
const src = 'C:\\projects\\app\\Users';
4
const files = fs.readdirSync(src);
5
β
6
for (const file of files) {
7
fs.rename(oldPath, newPath, callback);
8
}
Note:
If the
newPath
already exists, it will be overwritten.
Let's say we have the following project structure:
xxxxxxxxxx
1
/app/
2
βββ Users/
3
βββ usr1.js
4
βββ usr2.js
5
βββ usr3.js
To rename usr.js files we will use:
for...of
statement to iterate the Users/ directory,fs.readdirSync()
to get the file names from Users/ directory,fs.rename()
to actually rename the usr.js files.
xxxxxxxxxx
1
const fs = require('fs');
2
β
3
const src = 'C:\\projects\\app\\Users';
4
const files = fs.readdirSync(src);
5
β
6
for (const file of files) {
7
if (file.startsWith('usr')) {
8
fs.rename(
9
src + '/' + file,
10
src + '/' + file.replace('usr', 'user'),
11
err => {
12
console.error(err)
13
}
14
)
15
}
16
}
Result:
xxxxxxxxxx
1
/app/
2
βββ Users/
3
βββ user1.js
4
βββ user2.js
5
βββ user3.js