OneBite.Dev - Coding blog in a bite size

loop and rename all files inside a folder in Nodejs

Here is how to rename all files inside a certain folder with Javascript (NodeJS).

Here is how you can rename all files inside a certain folder with Javascript (NodeJS). This code sample assume you have a file named “how-to-xxxxxx” and want to remove the how-to string at start.

You can replace the how-to string with any string you want

// Import the required modules
const fs = require('fs');
const path = require('path');

// Define source and destination directories
const sourceDir = './source';
const destinationDir = './dist';

// Create freshjs directory if it doesn't exist
if (!fs.existsSync(destinationDir)) {
  fs.mkdirSync(destinationDir);
}

// Read the directory
fs.readdir(sourceDir, (err, files) => {
  if (err) throw err;

  files.forEach(file => {
    // Read each file
    fs.readFile(path.join(sourceDir, file), 'utf8', (err, data) => {
      if (err) throw err;

      // Write the new file in freshjs directory
      // replace how-to with any text
      fs.writeFile(path.join(destinationDir, file.replace(/how-to-/g, '')), modifiedData, 'utf8', (err) => {
        if (err) throw err;
        console.log('File has been saved!');
      });
    });
  });
});

Please make sure you are running this script with Node.js. Be careful and ensure you have a backup of your files before running the script.

run with node filename.js

javascript