5

用nodejs 替换文件中所有图片的url

 2 years ago
source link: https://www.cnblogs.com/windofelegant/p/4164848.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

  博客园  ::

首页  ::

新随笔  ::

联系 ::

订阅

 ::

管理

  12 随笔 :: 0 文章 :: 1 评论 ::

10196 阅读

因业务需求,大量文件需要替换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;
则这条不会替换。
代码灵活应用,你可以改成替换其他东西。

<em id="__mceDel"><em id="__mceDel"><em id="__mceDel"><em id="__mceDel"></em></em></em></em>
/**
* 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)
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK