当前位置: 首页 > 后端技术 > Node.js

nodejs学习使用nodejs实现rm-cp-mv命令

时间:2023-04-03 23:51:07 Node.js

闲来无事,抱着学习nodejs的心态写点小东西,使用nodejsapi实现rm、cp、mv简单的删除/复制/移动文件/文件夹。用rm删除文件其实很简单。如果是文件,直接用fs.unlinkSync删除。如果是文件夹,递归一个一个删除。constfs=require("fs");const{join}=require("path");module.exports=asyncfunctiondeleteFiles(path){//检查路径是否真的存在if(!fs.existsSync(path)){console.warn(newError("路径不存在。"));return;}constfile=fs.lstatSync(path);//是文件,直接删除if(file.isFile()){fs.unlinkSync(path);return;}//是文件夹,遍历下面的所有文件在之前的项目中我不想删除隐藏文件,所以我在开头过滤文件if(fileName.startsWith(".")){continue;}constp=join(path,fileName);constf=fs.lstatSync(p);//是文件,直接删除if(f.isFile()){fs.unlinkSync(p);}//是文件夹,递归调用deleteFilesif(f.isDirectory()){awaitdeleteFiles(p);//file文件夹里面的文件删除后,删除文件夹fs.rmdirSync(p);}}}return;}};?cpCopyingafileCopyingafile有点多删除一个副本,需要判断oldPath是文件还是文件夹,newPath是文件还是文件夹,然后针对不同情况生成可用路径。constfs=require("fs");const{join,dirname,basename}=require("path");module.exports=asyncfunctioncopyFiles(oldPath,newPath){//判断路径是否存在,存在如果(!fs.existsSync(oldPath)||!fs.existsSync(newPath)){console.warn(newError("Thepathdoesnotexist."));返回;}constoldFile=fs.lstatSync(oldPath);constnewFile=fs.lstatSync(newPath);//如果oldPath是文件,则直接复制oldPathif(oldFile.isFile()){//需要考虑newPath是文件还是目录//如果是文件路径,则可以直接复制//如果是目录路径,需要拼接oldPath的文件名if(newFile.isDirectory()){newPath=join(newPath,basename(oldPath));}fs.copyFileSync(oldPath,newPath);返回;}//如果oldPath是目录,newPath也应该是目录//如果newPath的目标路径是文件,默认复制到文件所在目录if(newFile.isFile()){console.warn(newError("参数2应该是路径。"));newPath=dirname(newPath);}if(oldFile.isDirectory()){constfiles=awaitfs.readdirSync(oldPath);if(files&&files.length){//遍历目录下的所有文件,并在目录路径上拼接fileNamefiles.forEach(async(fileName)=>{constoPath=join(oldPath,fileName);constoFile=fs.lstatSync(oPath);//如果拼接的路径是文件,然后直接Copyif(oFile.isFile()){//当然新文件也需要和fileName拼接constnewFile=join(newPath,fileName);fs.copyFileSync(oPath,newFile);}//如果是目录,则递归调用moveFilesif(oFile.isDirectory()){constoldDir=join(oldPath,fileName);constnewDir=join(newPath,fileName);//需要判断是否是这个拼接后的newDir中存在目录,并创建files移动文件可以偷懒,先调用copyFiles函数复制文件,然后调用deleteFiles删除文件就是移动了哈哈哈constcopyFiles=require("./copy");constdeleteFiles=require("./delete");module.exports=asyncfunctionmoveFiles(oldPath,newPath){copyFiles(oldPath,newPath).then((res)=>{deleteFiles(oldPath);});};使用yarn命令调用当然,为了更逼真,可以在package.json中配置rm/mv/cp,这样会更像。"scripts":{"rm":"node./rm.js","mv":"node./mv.js","cp":"node./cp.js"}这样直接配置肯定会不行是的,我们还需要读取命令的输入,使用node自带的进程读取命令传递的参数//cp.jsconstcopyFiles=require("./copy");copyFiles(process.argv[2],process.argv[3]);//mv.jsconstmoveFiles=require("./move");moveFiles(process.argv[2],process.argv[3]);//rm.jsconstdeleteFiles=require('./delete')deleteFiles(process.argv[2])最后可以使用yarnrm/cp/mvxxxxxx的形式体面使用。#删除文件yarnrm./a.js#删除目录yarnrm./a#移动单个文件yarnmv./a.js./b.js#第二个参数为目录时,a.js文件名为自动取yarnmv./a.js./b#移动目录下的所有文件yarnmv./a./b#复制文件yarncp./a/a.js./b/b.js#当第二个参数是一个目录。js文件名yarncp./a/a.js./b#复制目录下的所有文件yarncp./a./b