Clue Mediator

Rename all files in a folder using Node.js

๐Ÿ“…July 2, 2023
๐Ÿ—Node.js

Renaming multiple files in a folder can be a tedious task, but fret not! In this article, we'll explore different ways to rename files using the power of Node.js. Whether you want to add a prefix, suffix, or completely change the file names, we've got you covered!

Rename all files in a folder

server.js

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

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

    for (const file of files) {
      const fileInfo = path.parse(file);

      const oldPath = path.join(__dirname, folderPath, file);
      const newPath = path.join(__dirname, folderPath, `${fileInfo.name}_new${fileInfo.ext}`);

      await fs.rename(oldPath, newPath);
    }
  } catch (error) {
    // Handle error here
    console.log(error);
  }
};

app.get('/', (req, res) => {
  renameFiles('./images');
  res.send('DONE!')
});

It starts by importing the required modules, path and fs.promises. The renameFiles function, defined as an async function, reads all files in the specified folder using fs.readdir and iterates over each file. It extracts file information using path.parse and constructs the old and new file paths using path.join. Finally, it uses fs.rename to perform the file renaming operation. Any errors that occur are caught and logged.

Overall, this code efficiently renames files in a folder by utilizing the path and fs.promises modules in Node.js.

Conclusion

Renaming files in a folder using Node.js can save you a lot of time and effort. Whether you want to organize your files or make bulk changes, the techniques we've discussed will come in handy. Feel free to experiment with different approaches and find what suits your needs best.

Happy coding and keep exploring the amazing capabilities of Node.js!

"Coding is not just about creating something functional; it's about the joy of building something that comes to life." - Unknown

Demo & Source Code

GitHub Repository