/*
将静态资源css,js上传至cdn并替换
*/
const fs = require('fs');
const rp = require('request-promise');
const glob = require('glob');
//上传文件并获取url
async function uploadFile(filePath) {
var options = {
method: 'POST',
url: 'http://xxxx.xxx.com/api/upload', //换成你自己的cdn
formData: {
contentType: 'text/css',
needHttps: 'true',
file: fs.createReadStream(filePath),
},
};
// console.log(rp(options))
return await rp(options).then(res => JSON.parse(res).data);
}
//读取文件,并且替换文件中指定的字符串
function replaceFile(filePath, sourceRegx, targetStr) {
fs.readFile(filePath, function(err, data) {
if (err) {
return err;
}
let str = data.toString();
str = str.replace(sourceRegx, targetStr);
fs.writeFile(filePath, str, function(err) {
if (err) {
console.log(err);
return err;
}
});
});
}
//遍历statics文件夹,找到main_*.js
function findFile(dir, filenameReg, cb) {
fs.readdir(dir, function(err, files) {
if (err) {
return err;
}
if (files.length != 0) {
files.forEach(item => {
let path = dir + '/' + item;
//判断文件的状态,用于区分文件名/文件夹
fs.stat(path, function(err, status) {
if (err) {
return err;
}
let isFile = status.isFile(); //是文件
let isDir = status.isDirectory(); //是文件夹
if (isFile) {
if (item.match(new RegExp(filenameReg))) {
// console.log('找到了', path);
// arr.push(path);
cb(path);
}
}
if (isDir) {
findFile(path, filenameReg, cb);
}
});
});
}
});
}
function test() {
findFile('./build', '^main.*css$', function(css) {
uploadFile(css).then(url => {
console.log('----', url);
});
});
}
// 替换静态资源
function replaceMainCss(htmls) {
findFile('./build', '^main.*css$', function(path) {
console.log(path);
uploadFile(path).then(url => {
console.log(url);
htmls.forEach(html => {
replaceFile(html, /\/static\/css\/main.[a-z0-9]{8}.css/, url);
});
});
});
}
function replaceMainJs(htmls) {
findFile('./build', '^main.*js$', function(path) {
console.log(path);
uploadFile(path).then(url => {
console.log(url);
htmls.forEach(html => {
replaceFile(html, /\/static\/js\/main.[a-z0-9]{8}.js/, url);
});
});
});
}
function replaceBaseJs(htmls) {
findFile('./build', '^base.*js$', function(path) {
console.log(path);
uploadFile(path).then(url => {
console.log(url);
htmls.forEach(html => {
replaceFile(html, /\/static\/js\/base.[a-z0-9]{8}.js/, url);
});
});
});
}
let htmls = [];
glob.sync('./build/**/index.html').forEach(html => {
htmls.push(html);
});
// console.log(htmls)
replaceMainCss(htmls);
replaceMainJs(htmls);
replaceBaseJs(htmls);
// test()
node实现前端静态资源的cdn自动化
于 2023-02-09 15:49:39 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)