const fs = require('fs');
const path = require('path');
const filePath = `${path.resolve('fontsvg')}/build`
//判断文件夹是否存在
const isDirectory = (filePath) =>{
return new Promise((resolve,reject) => {
fs.access(filePath, (err) => {
if(err){
resolve('faild')
}
resolve('ok')
})
})
}
//创建文件夹
const creactMkdir = (filePath) =>{
return new Promise((resolve,reject) => {
fs.mkdir(filePath, (err) => {
if(err){return}
resolve(true)
})
})
}
const writeSvg = (filePath) => {
console.log('读取处理中...')
fs.readFile(`${path.resolve('fontsvg')}/iconfont.js`, 'utf8', (err, data) => {
if (err) {
} else {
const svgArr = data.split('</symbol>');
svgArr.pop();
let svgTmp = '';
let viewBox = '';
svgArr.forEach((svg) => {
const tmpPath = svg.split('<path');
const viewBoxKey = tmpPath[0].match('id=.*"')[0].split('"')[1].replace('icon-', '').replace(/-(\w)/g, x => x.slice(1).toUpperCase());
const viewBoxValue = tmpPath[0].match('viewBox=.*"')[0].split('"')[1];
if (viewBoxValue !== '0 0 1024 1024') {
viewBox[viewBoxKey] = viewBoxValue;
viewBox += ` ${viewBoxKey}: '${viewBoxValue}',\n`;
}
const pathArr = [];
tmpPath.shift();
tmpPath.forEach((path) => {
pathArr.push(`{${path.replace(/=/g, ': ').replace('fill', ', fill').replace('></path>', '')}}`);
});
svgTmp += ` ${viewBoxKey}: [${pathArr}],\n`;
});
const svgStr = `export default {\n${svgTmp}\n}`;
fs.writeFile(`${filePath}/iconfont.svg.js`, svgStr, 'utf8',() => {
if (err) return
console.log('写入成功')
});
}
})
}
async function WriteFontSvg () {
const directory = await isDirectory(filePath)
if(directory == 'ok'){
writeSvg(filePath)
}else{
const creact= await creactMkdir(filePath)
if(creact){
console.log('创建成功')
writeSvg(filePath)
}
}
}
WriteFontSvg()