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);
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) {}
}
});
下面是完整代码
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
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()
})()
生成的结构如下图:
