вторник, 23 декабря 2025 г.

JavaScript Node.js Replace in files

const fs = require('fs');

const path = require('path');


const folderPath = path.resolve(__dirname, './folder');


function walkDirAndReplace (folderPath) {

   fs.readdirSync(folderPath).forEach(function (filesOrFolder) {

        const fileOrFolderPath = path.join(folderPath, filesOrFolder);

        const stats = fs.statSync(fileOrFolderPath);

        if (stats.isDirectory()) {

            walkDirAndReplace(fileOrFolderPath);

        } else if (stats.isFile() && fileOrFolderPath.endsWith('slice.ts')) {

            fs.writeFileSync(

                fileOrFolderPath,

                fs.readFileSync(fileOrFolderPath).toString().replace(/const\s(\w)(\w+)Slice(\s=\screateSlice\(\{)/g, function (match, $1, $2, $3) {

                    return 'const ' + $1 + $2 + 'Slice: Slice<' + $1.toUpperCase() + $2 + 'StateInterface>' + $3;

                })

            );

        }

    });

}


walkDirAndReplace(folderPath);

Комментариев нет:

Отправить комментарий