Node js Rename All Files in Folder Tutorial

Node js Rename All Files in Folder Tutorial

You may need to use Node.js to rename all files in a folder when you want to automate the process of renaming multiple files in a directory, The easiest way to rename a file based on its name, extension, size and type in Node JS is to use fs.rename().

This can be useful for a variety of purposes, such as organizing files, standardizing naming conventions, or preparing files for further processing. Node.js provides a convenient way to iterate through files in a folder, modify their names, and perform mass rename operations, compared to manually renaming each file individually. Can save time and effort. This is especially useful when dealing with large numbers of files or when you need to apply frequent changes to their names.

In this tutorial, you will learn how to rename all files in folder with extension, type, size using node js.

How to Rename All Files in Folder using Node js

Here are some methods to rename all files in a folder with extension, type and size using Node.js:

  • 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

AuthorAdmin

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 *