Node js Rename All Files in Folder Tutorial

The easiest way to rename a file based on its name, extension, size, and type in Node JS using fs.rename(). In this tutorial, you will learn how to rename all files in a folder with extension, type, and size using node js.

How to Rename All Files in Folder using Node js

Here are some methods:

  • Method 1: Using fs.readdir and fs.rename (Callback-based)
  • Method 2: Using Promises with fs.promises (Node.js 10+)
  • Method 3: Rename All Files in Folder with Extension

Method 1: Using fs.readdir and fs.rename (Callback-based)

You can rename all files in a folder in Node.js using fs.readdir and fs.rename (Callback-based). Here is an example to do this:

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

const folderPath = 'path_to_your_folder'; // Update with the path to your folder

fs.readdir(folderPath, (err, files) => {
  if (err) {
    console.error(err);
    return;
  }

  files.forEach((file, index) => {
    const oldFilePath = path.join(folderPath, file);
    const newFileName = `newName_${index}.ext`; // Update the renaming logic as per your requirements
    const newFilePath = path.join(folderPath, newFileName);

    fs.rename(oldFilePath, newFilePath, (err) => {
      if (err) {
        console.error(`Error renaming ${file}: ${err}`);
      } else {
        console.log(`Renamed ${file} to ${newFileName}`);
      }
    });
  });
});

Method 2: Using Promises with fs.promises (Node.js 10+)

You can rename all files in a folder in Node.js using Promises with fs.promises. Here is an example to do this:

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

async function renameFilesInFolder() {
  const folderPath = 'path_to_your_folder'; // Update with the path to your folder

  try {
    const files = await fs.readdir(folderPath);

    for (let index = 0; index < files.length; index++) {
      const file = files[index];
      const oldFilePath = path.join(folderPath, file);
      const newFileName = `newName_${index}.ext`; // Update the renaming logic as per your requirements
      const newFilePath = path.join(folderPath, newFileName);

      await fs.rename(oldFilePath, newFilePath);
      console.log(`Renamed ${file} to ${newFileName}`);
    }
  } catch (err) {
    console.error(err);
  }
}

renameFilesInFolder();

Method 3: Rename All Files in Folder with Extension

To rename all files with a specific extension in a folder using Node.js, you can use the fs module to read the files in the folder, filter them based on their extension, and then use the fs.rename() method to rename each file. Here’s a simple example of how you can do this:

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

// Define the folder path and the target extension
const folderPath = './your-folder-path'; // Change this to the path of your folder
const targetExtension = '.jpg'; // Change this to the extension you want to rename

// Function to rename all files in the folder with the target extension
function renameFilesInFolder(folderPath, targetExtension) {
  fs.readdir(folderPath, (err, files) => {
    if (err) {
      console.error('Error reading folder:', err);
      return;
    }

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

      // Check if the file has the target extension
      if (path.extname(file) === targetExtension) {
        // Construct the new file name (you can modify this as needed)
        const newFileName = 'newPrefix_' + file;

        // Construct the new file path
        const newFilePath = path.join(folderPath, newFileName);

        // Rename the file
        fs.rename(filePath, newFilePath, (err) => {
          if (err) {
            console.error(`Error renaming ${file}:`, err);
          } else {
            console.log(`Renamed ${file} to ${newFileName}`);
          }
        });
      }
    });
  });
}

// Call the function to rename files
renameFilesInFolder(folderPath, targetExtension);

Conclusion

That’s it; you have learned how to rename all files in folder with extension, type, size using node js.

Recommended Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *