標籤:des blog http io ar sp for java on
因業務需求,大量檔案需要替換url到不同的環境。
所以用nodejs寫了這個。本來想用python寫,但是大部分同事只有nodejs環境。
主要的命令node rurl.js -new http://www.g.cn/
替換原有.png .jpg圖片圖片路勁到 http://www.g.cn/
比如原來是 background:url(http://www.yoursite.com/a/b/c/d.png);
會指定到
background:url(http://www.g.cn/d.png);
如果某url加上!important.
如:
background:url(http://www.yoursite.com/a/b/c/d.png) !important;
則這條不會替換。
代碼靈活應用,你可以改成替換其他東西。
/** * replace image url script. * you can input command like "node rurl.js -new http://www.g.cn/" to use it. * any css includes "!important" will not be effected. *///your new replace url var arguments = process.argv.slice(2);var command = arguments[0]+"";var newReplaceUrl = arguments[1]+"";if(command != ‘-new‘ || newReplaceUrl == null){ throw ‘please input your new url. Eg: node rurl.js -new https://www.g.cn/‘;} var fs = require(‘fs‘);var files = ["bank.css", "wallet.css"];var URL_REG = /url\(.*?;/g;var PIC_REG = /url\(.*?(?=[A-Za-z_\-0-9]*(\.png|\.jpg))/;for(var i=0;i<files.length;i++){ var file = files[i]; (function (_file){ fs.readFile(_file,function (err,data){ data = data + ""; data = data.replace(URL_REG,function (word){ if(word.indexOf("important") != -1){ return word; }else{ var url = "url(" + newReplaceUrl; return word.replace(PIC_REG, url); } }); fs.writeFile(_file, data, function(err){ if(err){ console.log("error!" + _file); }else{ console.log("success!" + _file); } }); }) })(file)}
用nodejs 替換檔案中所有圖片的url