nodejs遍历文件夹下并操作HTML/CSS/JS/PNG/JPG的方法
需求描述,由于工作的需要,需要将原本用于1280720的网页改为19201080的网页(电视端页面)。需求可以拆分为两部分,代码部分的修改以及图片的修改。在代码部分,需要将所有位置以及大小相关的值乘以1.5,图片的尺寸也要放大1.5倍。
首先使用nodejs遍历当前的文件夹:
//遍历所有的文件
varfs=require("fs")
varpath=require("path")
varrelativePath='\\test'
//拿到需要遍历的路径
varroot=path.join(__dirname)+relativePath
readDirSync(root)
//使用异步获取路径
//参数是遍历文件的根路径
functionreadDirSync(path){
varpa=fs.readdirSync(path);
//循环遍历当前的文件以及文件夹
pa.forEach(function(ele,index){
varinfo=fs.statSync(path+"\\"+ele)
if(info.isDirectory()){
//console.log("dir:"+ele)
readDirSync(path+"\\"+ele);
}else{
varfilePath=path+'\\'+ele;
//找到.css.html.js文件
letfileNameReg=/\.css|\.js|\.html|\.htm/g;
letshouldFormat=fileNameReg.test(filePath);
if(shouldFormat){
console.log('findfile:',filePath);
//这里就拿到了符合条件的文件路径,后面就可以根据这个路径来执行相关的操作
}
}
})
}
如果是HTMLCSSJS文件使用nodejs文件相关api来操作文件,首先是读取到文件,然后是写入文件。代码:
varformatObj=newChangePosFor4K();//创建对象,构造函数在下文尾部
functionreadFile(params){
//读取文件示例
fs.readFile(params,function(err,data){
if(err){
console.log('happenanerrorwhenreadfile,erroris'+err)
}
else{
varcodeTxt=data.toString();
//使用对象来修改文件内容,执行位置以及大小相关值的扩大操作
varformatReturn=formatObj.formatNumber(codeTxt);
codeTxt=formatReturn.code;
//给不同的文件添加不同的注释
letjsFileReg=/.js$/i;
lethtmlFileReg=/.html$|.htm$/i;
letcssFileReg=/.css$/i;
lettip1='autoformattingtoolhascheckthisfile.'
lettip2='blockhasbeenhandleinthiscode.'
letnow=newDate();
if(jsFileReg.test(params)||cssFileReg.test(params)){
codeTxt+='\n/*'+tip1+'*/'
codeTxt+='\n/*'+formatReturn.times+''+tip2+'at'+now+'*/'
}elseif(htmlFileReg.test(params)){
codeTxt+='\n'
codeTxt+='\n'
}
//将修改好内容写入当前路径的文件
writeFile(params,codeTxt);
}
})
}
//写入文件
//fs.writeFile(file,data[,options],callback)
//file-文件名或文件描述符。
//data-要写入文件的数据,可以是String(字符串)或Buffer(流)对象。
//options-该参数是一个对象,包含{encoding,mode,flag}。默认编码为utf8,模式为0666,flag为'w'
//callback-回调函数,回调函数只包含错误信息参数(err),在写入失败时返回。
functionwriteFile(_path,_txt){
fs.writeFile(_path,_txt,function(err){
if(err){
console.log('happenanerrorwhenwritefile,erroris'+err)
}
else{
console.log("formatfilesuccess:",_path);
}
})
}
//样式操作相关
/*
*fun:
*/
functionChangePosFor4K(){
varformat=/\d+px/gi;
vartempSufixx='@@'//临时占位符,因为需要靠数字+px的正则来匹配,已经修改过的就不能再有px
this.formatNumber=function(arg){
//匹配出所有的数字和px的组合dd.px
varinitalStr=arg;
varlocIndex=initalStr.search(format);//获取到起始索引
varchangeTimes=0;
while(locIndex>0){
//拿到值
varlocStr=getFullPos(initalStr,locIndex);
//乘以相关比例
varlocValue=Math.ceil(parseInt(locStr)*1.5);
varlocReplaceStr=locValue+tempSufixx;
//替换
initalStr=replaceStr(initalStr,locIndex,locStr.length,locReplaceStr);
locIndex=initalStr.search(format);
//计数
changeTimes++;
}
varlocReg=newRegExp(tempSufixx,'gi')
initalStr=initalStr.replace(locReg,'px');
return{code:initalStr,times:changeTimes};
}
//根据字符串和起始位置找到xxx.px字符串
functiongetFullPos(_str,_begin){
varoutput='';
while(output.indexOf('px')<0){//当没有没有找到完整的字符串
output+=_str.charAt(_begin);
_begin++;
}
returnoutput;
}
//被替换的元素,根据起始索引,替换长度,替换元素
functionreplaceStr(_str,_begin,_len,_subStr){
//首先将字符串和拼接字符串转化为数组
varstrArr=_str.split('');
varsubStrArr=_subStr;
//完成替换
strArr.splice(_begin,_len,subStrArr);
returnstrArr.join('');
}
}
至此代码相关操作就已经结束了,下面来图片操作。这里的图片操作借助了gm,首先通过npm安装gm,并安装ImageMagick或者GraphicsMagick软件。代码:
varfs=require('fs');
//两个图片操作底层程序可以选择
vargm=require('gm').subClass({ImageMagick:true});
varpath=require("path")
varrelativePath='\\test'
varroot=path.join(__dirname)+relativePath
//放大图片并制作副本
functionmagnifyImg(_path){
//获取当前图片的长和宽
//将长和宽放大1.5倍
//设置新的图片大小
//没有直接调用magnify,因为magnify不支持小数
gm(_path)
.size(function(err,size){
if(!err){
//console.log(size.width>size.height?'wider':'tallerthanyou');
letnowWidth=parseInt(size.width);
letnowHeight=parseInt(size.height);
letmagnifyWidth=Math.floor(nowWidth*1.5);
letmagnifyHeight=Math.floor(nowHeight*1.5);
gm(_path).resizeExact(magnifyWidth,magnifyHeight).write(_path,function(err){
if(!err)
console.log(_path+'done');
else
console.log(_path+'fail'+err);
})
}
else{
console.log('getsizehaserror'+_path+'anderris:'+err);
}
})
}
至此,功能就完成了。
比较有感触的是在操作代码中相关位置以及大小的实现过程,花了一些心思。图片的操作就是百度之后根据别人写的来做的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。