node脚本(使用git里面的提交号作为文件的版本号)

给html中的js、css添加版本号,解决浏览器缓存引起的问题

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(.*?)href\s*=\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(.*?)src\s*=\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);

**注: 这里需要在linux或者在git

标签: none

添加新评论