rename file javascript code example
Example 1: rename file in js
var fs = require('fs');
fs.rename('sample_old.txt', 'sample_new.txt', function (err) {
if (err) throw err;
console.log('File Renamed.');
});
Example 2: rename a file using node.js
const { join } = require('path');
const { readdirSync, renameSync } = require('fs');
const [dir, search, replace] = process.argv.slice(2);
const match = RegExp(search, 'g');
const files = readdirSync(dir);
files
.filter(file => file.match(match))
.forEach(file => {
const filePath = join(dir, file);
const newFilePath = join(dir, file.replace(match, replace));
renameSync(filePath, newFilePath);
});