[toc]创建时间:2019-08-12注:在win10、v10.16.1环境下运行没有问题首先导入相关包(使用处会注明):constfs=require('fs')constpath=require('path')constchild_process=require('child_process')constfsEx=require('fs-extra')/***@des这个包是一个实验性的API*/constfsPromises=require('fs')。promisespair复制文件有三种方法:使用writeFileSync和readFileSync结合使用copyFileSync和使用promises的copyFile方法。同步方式或异步方式可酌情更改,实现代码如下复制文件的地址,相对地址)*/functioncopyFile(copiedPath,resultPath){copiedPath=path.join(__dirname,copiedPath)resultPath=path.join(__dirname,resultPath)try{/***@des方法1*///fs.writeFileSync(resultPath,fs.readFileSync(copiedPath))/***@des方法2*///fs.copyFileSync(copiedPath,resultPath)console.log('成功');}赶上(错误){console.log(错误);}/***@des方法3*/fsPromises.copyFile(copiedPath,resultPath).then(()=>{console.log('success');}).catch((err)=>{console.log(err);});}删除文件使用unlinkSync方法实现代码如下/***@param{delPath:String}(要删除的文件的地址)*@param{direct:Boolean}(是否需要处理该地址)*/functiondeleteFile(delPath,直接){delPath=直接?delPath:path.join(__dirname,delPath)try{/***@des判断文件或文件夹是否存在*/if(fs.existsSync(delPath)){fs.unlinkSync(delPath);}else{console.log('不存在路径:',delPath);}}catch(error){console.log('delerror',error);}}对文件夹(目录)的操作以下代码有参考,复制文件夹的相关方法复制文件有两种方式:child_process递归读取文件和文件夹然后在指定地址创建实现代码及解释如下:/***@des参数解释同上*/functioncopyFolder(copiedPath,resultPath,direct){if(!direct){copiedPath=path.join(__dirname,copiedPath)resultPath=path.join(__dirname,resultPath)}函数createDir(dirPath){fs.mkdirSync(dirPath)}if(fs.existsSync(copiedPath)){createDir(resultPath)/***@des方法一:使用子进程操作命令行*///child_process.spawn('cp',['-r',copiedPath,resultPath])/***@des方法2:*/constfiles=fs.readdirSync(copiedPath,{withFileTypes:true});for(leti=0;i
