const fs = require('fs');
const rp = require('request-promise');
const glob = require('glob');
async function uploadFile(filePath) {
var options = {
method: 'POST',
url: 'http://xxxx.xxx.com/api/upload',
formData: {
contentType: 'text/css',
needHttps: 'true',
file: fs.createReadStream(filePath),
},
};
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;
}
});
});
}
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))) {
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);
});
replaceMainCss(htmls);
replaceMainJs(htmls);
replaceBaseJs(htmls);