How to Rename Files in Node.js

Node.js provides a built-in module, fs, for managing file systems, including renaming files.

Let's see how:

Using fs.rename

The fs.rename method is asynchronous and takes three parameters: the current filename, the new filename, and a callback function. The callback function executes after the rename operation completes and handles any errors that might occur:

const fs = require('node:fs');

fs.rename('oldFileName.txt', 'newFileName.txt', function(err) {
    if (err) throw err;
    console.log('File renamed successfully');
});

Multiple Files

To rename multiple files, use fs.readdir to list files in a directory, then apply fs.rename within a loop:

const fs = require('node:fs');

fs.readdir('./data/', (err, files) => {
    if (err) throw err;

    files.forEach(file => {
        if (file.endsWith('.txt')) {
            const newName = file.replace('.txt', '.renamed.txt');
            fs.rename(`./data/${file}`, `./data/${newName}`, err => {
                if (err) throw err;
                console.log(`${file} was renamed to ${newName}`);
            });
        }
    });
});

Synchronous with fs.renameSync

For those preferring synchronous operations, fs.renameSync avoids callbacks but requires try-catch for error handling:

try {
    fs.renameSync('oldFileName.txt', 'newFileName.txt');
    console.log('File renamed successfully');
} catch (err) {
    console.error('Error occurred:', err);
}

Gotchya

You'll still need permission to alter files, so ensure the Node.js process has appropriate permissions to read and write files.

Nodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.