html 中加入node.js,关于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(//gi, ($0, $1, $2, $3, $4, $5) => {

if (/^s*http[s]{0,1}:///i.test($3)) {

return $0;

} else {

return ``;

}

}).replace(//gi, ($0, $1, $2, $3, $4, $5) => {

if (/^s*http[s]{0,1}:///i.test($3)) {

return $0;

} else {

return ``;

}

});

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);

本文由乐趣区整理发布,转载请注明出处,谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值