用nodejs 替换文件中所有图片的url
因业务需求,大量文件需要替换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)
}
posted on 2014-12-15 14:43 风之优雅z 阅读(...) 评论(...) 编辑 收藏