Published

Node JS File Name and Extension Changer

Authors
  • avatar
    Name
    xNoJustice

The file extension change method

file-extension-changer.js
const { readdirSync, rename, lstatSync } = require("fs");
const path = require("path");

const mainFolder = "./compressed";
const oldPath = ".jpeg";
const newPath = ".webp";

readdirSync(mainFolder).forEach((folder) => {
  if (lstatSync(`${mainFolder}/${folder}`).isDirectory()) {
    readdirSync(`${mainFolder}/${folder}`).forEach((file2) => {
      rename(
        `${mainFolder}/${folder}/${path.parse(file2).name}${oldPath}`,
        `${mainFolder}/${folder}/${path.parse(file2).name}${newPath}`,
        (err) => {
          if (err) console.log(err);
          console.log("Rename complete!");
        }
      );
    });
  } else {
    readdirSync(`${mainFolder}`).forEach((file2) => {
      rename(
        `${mainFolder}/${path.parse(file2).name}${oldPath}`,
        `${mainFolder}/${path.parse(file2).name}${newPath}`,
        (err) => {
          if (err) console.log(err);
          console.log("Rename complete!");
        }
      );
    });
  }
});
// compressed/test.jpeg to compressed/test.webp

The file name change method

file-name-changer.js
const { readdirSync, rename, lstatSync } = require("fs");
const path = require("path");
const uuid = require("uuid");

const mainFolder = "./compressed";

readdirSync(mainFolder).forEach((folder) => {
  if (lstatSync(`${mainFolder}/${folder}`).isDirectory()) {
    readdirSync(`${mainFolder}/${folder}`).forEach((file2) => {
      rename(
        `${mainFolder}/${folder}/${path.parse(file2).name}${
          path.parse(file2).ext
        }`,
        `${mainFolder}/${folder}/${uuid.v4().toString()}${path.parse(file2).ext}`,
        (err) => {
          if (err) console.log(err);
          console.log("Rename complete!");
        }
      );
    });
  } else {
    readdirSync(`${mainFolder}`).forEach((file2) => {
      rename(
        `${mainFolder}/${path.parse(file2).name}${path.parse(file2).ext}`,
        `${mainFolder}/${uuid.v4().toString()}${path.parse(file2).ext}`,
        (err) => {
          if (err) console.log(err);
          console.log("Rename complete!");
        }
      );
    });
  }
});
// compressed/test.webp to compressed/9756eff2-1714-4c0d-b88f-88361fa9e2ca.webp