node.js example - how to change the file extensions of all files in a folder

Node.js example - how to change the file extensions of all files in a folder


Navigation


Node.js can be a good choice for simple file manipulation tasks on Windows that may occur on a daily basis.
It has many advantages, such as the fact that it offers a built-in module called fs that provides a wide range of file manipulation functions, such as reading, writing, deleting, and copying files. This module simplifies working with files and makes it easy to carry out various file-related tasks without needing external libraries.

The following example shows how to change the file extensions of all files in a folder with the extension .jpeg to .jpg


const fs = require('fs');
const path = require('path');

const folderPath = '/your/folder';

fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('Error reading folder:', err);
return;
}

files.forEach((file) => {
const filePath = path.join(folderPath, file);
const fileExt = path.extname(file);

if (fileExt === '.jpeg') {
const newFilePath = path.join(folderPath, path.basename(file, '.jpeg') + '.jpg');

fs.rename(filePath, newFilePath, (err) => {
if (err) {
console.error('Error renaming file:', err);
} else {
console.log(`${file} renamed to ${path.basename(newFilePath)}`);
}
});
}
});
});


Replace 'your/folder' with the actual path of the folder where you want to perform this renaming operation. This script reads the files in the specified folder, checks if the file extension is .jpeg, and if so, renames it to .jpg.