node脚本筛选文件,查找文件输出文本内容

526 阅读1分钟

1、利用glob模块匹配文件

function getDirectories (src, callback) {
    glob(src + '/**/*', callback);
}

2、利用fs模块读取文件

async function readFile (params) {
    return fs.readFile(params, 'utf8').then(e => {
        return {
            //  当前页面路径
            routeUrl: params,
            // 页面内容
            text: e 
        };
    });
}

3、遍历文件夹,查找文件中所需匹配的内容,我这里例子是匹配项目中所有的I18n字符(比如:A1001)

getDirectories(srcPath, async function (err, res) {
    if (err) {
        console.log('Error', err);
    } else {
        const map = new Map();
        for (let index = 0; index < res.length; index++) {
            const element = res[index];
            // 检查是否文件夹
            if (!fs.lstatSync(element).isDirectory()) {
                // 截取文件类型
                const lastIndex = element.lastIndexOf('.');
                const fileType = element.substring(lastIndex + 1, element.length);

                // 筛选文件
                if (fileType === 'vue' || fileType === 'js') {
                    const result = await readFile(element);
                    // 需要匹配的字段正则
                    const arr = result.text.match(/A[A-Z]*[0-9]{4,}/g);
                    //  利用Map对象插入每个路径下的匹配字段
                    if (!map.has(result.routeUrl)) {
                        if (arr) {
                            map.set(result.routeUrl, arr);
                        }
                    }
                }
            }
        }
        // 同步写文件

        // 这里需要注意下JSON.stringify不能直接转 
        try {
            fs.writeFileSync('./i18n.json', JSON.stringify(Array.from(map.entries())), 'utf8');
        } catch (e) {}
    }
});

下面是完整代码

const glob = require('glob');
// const path = require('path')
const fs = require('fs-extra');

const srcPath = './src';

// 匹配对应规则的文件
function getDirectories (src, callback) {
    glob(src + '/**/*', callback);
}

async function readFile (params) {
    return fs.readFile(params, 'utf8').then(e => {
        return {
            routeUrl: params,
            text: e
        };
    });
}

getDirectories(srcPath, async function (err, res) {
    if (err) {
        console.log('Error', err);
    } else {
        const map = new Map();
        for (let index = 0; index < res.length; index++) {
            const element = res[index];
            // 检查是否文件夹
            if (!fs.lstatSync(element).isDirectory()) {
                // 截取文件类型
                const lastIndex = element.lastIndexOf('.');
                const fileType = element.substring(lastIndex + 1, element.length);

                // 筛选文件
                if (fileType === 'vue' || fileType === 'js') {
                    const result = await readFile(element);
                    const arr = result.text.match(/A[A-Z]*[0-9]{4,}/g);
                    if (!map.has(result.routeUrl)) {
                        if (arr) {
                            map.set(result.routeUrl, arr);
                        }
                    }
                }
            }
        }
        // 同步写文件
        try {
            fs.writeFileSync('./i18n.json', JSON.stringify(Array.from(map.entries())), 'utf8');
        } catch (e) {}
    }
});
(async function main () {
    getDirectories();
})();

生成的结构如下图:

1667183297172.jpg