Node.js: renaming files recursively

In Node.js renaming multiple files recursively is quite a simple task.

We have a series of text files containing HTML code that we want to rename with the appropriate extension. We can write the following code:


'use strict';

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

const listDir = (dir, fileList = []) => {

    let files = fs.readdirSync(dir);

    files.forEach(file => {
        if (fs.statSync(path.join(dir, file)).isDirectory()) {
            fileList = listDir(path.join(dir, file), fileList);
        } else {
            if(/\.txt$/.test(file)) {
                let name = file.split('.')[0].replace(/\s/g, '_') + '.html';
                let src = path.join(dir, file);
                let newSrc = path.join(dir, name);
                fileList.push({
                    oldSrc: src,
                    newSrc: newSrc
                });
            }
        }
    });

    return fileList;
};

let foundFiles = listDir( './data');
foundFiles.forEach(f => {
   fs.renameSync(f.oldSrc, f.newSrc); 
});

listDir() is a recursive function. If the element found is a directory, it simply keeps on parsing. Otherwise if it's a text file, it collects the current path and the new path into an array of objects.

Prev Articles Next