Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Node.js Tutorial to Rename All Files in Directory With Custom Pattern Using fs Module

Posted on March 17, 2023

 

 

Sure, here’s a Node.js script that uses the fs module to rename all the files in a directory to img%d pattern:

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const fs = require('fs');
const path = require('path');
 
const directoryPath = './my-directory'; // change this to the path of your directory
const prefix = 'img'; // change this to the prefix you want to use
const extension = '.jpg'; // change this to the file extension you want to use
let counter = 1;
 
fs.readdir(directoryPath, (err, files) => {
  if (err) throw err;
  files.forEach((file) => {
    const oldPath = path.join(directoryPath, file);
    const newPath = path.join(directoryPath, prefix + counter + extension);
    fs.rename(oldPath, newPath, (err) => {
      if (err) throw err;
      console.log(`${oldPath} renamed to ${newPath}`);
    });
    counter++;
  });
});

 

 

In this code, the fs.readdir method is used to read the contents of a directory specified by the directoryPath variable. The forEach method is then used to loop through each file in the directory.

 

 

For each file, the fs.rename method is called to rename the file to the img%d pattern, where %d is replaced with a counter variable. The counter is incremented after each file is renamed.

 

 

The old and new paths of each file are constructed using the path.join method, which joins the directory path, filename, and extension.

 

 

Finally, a console message is printed for each file that is renamed.

 

 

Recent Posts

  • Node.js Tutorial to Rename All Files in Directory With Custom Pattern Using fs Module
  • FFMPEG Command to Create MP4 Video Slideshow From Multiple Images in Command Line
  • How to Add Let’s Encrypt SSL Certificate to Domain Using Certbot in Nginx
  • Node.js Fluent-FFMPEG Audio Pitch & Speed Changer With Live Preview in Browser Using Express
  • React.js react-awesome-modal Example to Show Popup Modal With Animation in Browser Using Javascript
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme