Answers for "how to rename for folder have file with fs express"

7

fs renaming files

const fs = require("fs")

fs.rename("./testfile.txt", "./newtestfile.txt", (err) => {
	if (err) console.log(err)
})
Posted by: Guest on November-22-2020
0

Rename files in a directory with node.js

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

const folderPath = "./assets";

// read all files in the directory
let filesArr = fs.readdirSync(folderPath);

// Loop through array and rename all files 

filesArr.forEach((file, index) => {
  let fullPath = path.join(folderPath, file);
  let fileExtension = path.extname(file);
  let fileName = path.basename(file, fileExtension);

  let newFileName = fileName + index + "." + fileExtension;
try {
  fs.renameSync(fullPath, path.join(folderPath, newFileName));
} catch (error) {
  console.error(error)
}
});
Posted by: Guest on February-07-2022

Code answers related to "Javascript"

Browse Popular Code Answers by Language