I have a folder with multiple files for ex. files with name old.html , old.txt , old.json and i want to rename all these files to new.html , new.txt , new.json. Is there any method present in node js which i can use here?
Asked
Active
Viewed 5,965 times
0
-
https://stackoverflow.com/questions/22504566/renaming-files-using-node-js – KLP Feb 25 '20 at 11:00
-
3Does this answer your question? [Renaming files using node.js](https://stackoverflow.com/questions/22504566/renaming-files-using-node-js) – DarkInk Oct 21 '21 at 18:35
3 Answers
7
This is what you are looking for:
const { join, extname, basename } = require('path');
const { readdirSync, renameSync } = require('fs');
for (const oldFile of readdirSync(pathToOldFolder)) {
const extension = extname(oldFile);
const name = basename(oldFile, extension);
if (name === 'old') {
renameSync(join(pathToOldFolder, oldFile), join(pathToOldFolder, 'new' + extension));
}
}
3
You could use the FS module?
Use the following to retrieve a list of files
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
then loop over them to rename the files
fs.rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});

Richard Price
- 482
- 4
- 13
0
check here, though it may not fulfil your requirement
Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.
like { file1: old.txt, file2: old.html, ... ... ... }
fs.readFile('/path/to/countries.json', function(error, data) {
if (error) {
console.log(error);
return;
}
var obj = JSON.parse(data);
for(var p in obj) {
fs.rename('/path/to/' + obj[p].split(".")[0] + obj[p].split(".")[1], '/path/to/' + 'new' + obj[p].split(".")[1], function(err) {
if ( err ) console.log('ERROR: ' + err);
});
}
});

ANIK ISLAM SHOJIB
- 3,002
- 1
- 27
- 36