Languages
[Edit]
EN

Node.js - rename multiple files

0 points
Created by:
lena
384

In this article, we would like to show you how to rename multiple files in Node.js.

Quick solution:

const fs = require('fs');

const src = 'C:\\projects\\app\\Users';
const files = fs.readdirSync(src);

for (const file of files) {
    fs.rename(oldPath, newPath, callback);
}

Note:

If the newPath already exists, it will be overwritten.

 

Practical example

Let's say we have the following project structure:

/app/
  └── Users/
        ├── usr1.js
        ├── usr2.js
        └── usr3.js

To rename usr.js files we will use:

  • for...of statement to iterate the Users/ directory,
  • fs.readdirSync() to get the file names from Users/ directory,
  • fs.rename() to actually rename the usr.js files.
const fs = require('fs');

const src = 'C:\\projects\\app\\Users';
const files = fs.readdirSync(src);

for (const file of files) {
    if (file.startsWith('usr')) {
        fs.rename(
            src + '/' + file,
            src + '/' + file.replace('usr', 'user'),
            err => {
                console.error(err)
            }
        )
    }
}

Result:

/app/
  └── Users/
        ├── user1.js
        ├── user2.js
        └── user3.js
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join