乐趣区

关于node.js:给html中的jscss添加版本号解决浏览器缓存

const fs = require("fs");
const {join, resolve} = require('path');
const execSync = require('child_process').execSync;
const {mergeUrl} = require('./url.utils');

const findPath = resolve('./dist/template');
const rootPath = resolve('./');

// 文件版本记录
const fileVersionNote = {};
const toComPath = path => path.replace(//g, '/');
// 获取版本号
const getVersion = (dir, fileName) => {let dirPathPart = toComPath(dir).split('/');
    dirPathPart.pop();
    let dirPath = dirPathPart.join('/');
    fileName = fileName.replace(/^s*(.*?)s*$/, '$1');
    if (!/^//.test(fileName)) {fileName = join(dirPath, fileName).replace(rootPath, '');
    }else{fileName = 'dist' + fileName;}
    
    return getGitCommitVersion(toComPath(fileName).replace(/^/(.*?)$/, '$1'));
}
// 获取 git 文件版本号
const getGitCommitVersion = (file) => {
    let gv = null;
    if(/?/.test(file)){file = file.replace(/^(.*?)?.*?$/, '$1');
    }
    let noteV = fileVersionNote[file]
    if (typeof noteV !== 'string' || noteV === '') {if (fs.existsSync(file)) {
            try {gv = execSync(`git log ${file} | grep commit | awk 'NR==1' | awk -F '''{print $2}'`);
                gv = gv.toString();} catch (error) {}}
        if (typeof gv !== 'string' || gv.length < 10) {console.log('版本号获取谬误', file);
            noteV = '';
        }else{noteV = gv.substr(0, 7);
            console.log('新文件 git 提交号:', file, noteV);
        }
        fileVersionNote[file] = noteV;
    }
    return noteV;
}

// 读取所有的 html
function findHtmlAndAddVersion(dir) {if (fs.existsSync(dir)) {fs.stat(dir, (err, stat) => {if (err || !stat) {return console.error('读取文件状态谬误', err);
            } else {if (stat.isFile()) {
                    // 只是读取 html 文件
                    if (/.htm(l){0,1}$/i.test(dir)) {fs.readFile(dir, 'utf8', (err, data) => {if (err) {return console.error('读取文件谬误', err);
                            } else {let html = data.replace(/<link(.*?)hrefs*=s*(['"])(.*?)2(.*?)>/gi, ($0, $1, $2, $3, $4, $5) => {if (/^s*http[s]{0,1}:///i.test($3)) {return $0;} else {return `<link${$1}href="${mergeUrl($3, { _gv: getVersion(dir, $3) })}"${$4}>`;
                                    }
                                }).replace(/<script(.*?)srcs*=s*(['"])(.*?)2(.*?)>(.*?)</script>/gi, ($0, $1, $2, $3, $4, $5) => {if (/^s*http[s]{0,1}:///i.test($3)) {return $0;} else {return `<script${$1}src="${mergeUrl($3, { _gv: getVersion(dir, $3) })}"${$4}>${$5}</script>`;
                                    }
                                });
                                fs.writeFileSync(dir, html, function (err) {if (err) {return console.error('文件写入失败', err);
                                    }
                                });
                            }
                        });
                    }
                } else if (stat.isDirectory()) {fs.readdir(dir, function (err, files) {if (err || !Array.isArray(files)) {return console.error('读取文件夹谬误', err);
                        } else {
                            files.forEach(file => {findHtmlAndAddVersion(join(dir, file));
                            });
                        }
                    });
                } else {console.error('文件类型辨认谬误', stat);
                }
            }
        });

    } else {console.error('文件夹不存在!!!', dir);
    }
}


// 增加版本号
findHtmlAndAddVersion(findPath);
退出移动版