Node.js实用小工具——自动化Copy文件

196 阅读1分钟

有时候我们会遇到将一个磁盘的文件copy到另一个磁盘的问题,数量少的话手动还好,但是数量大的话手动未免有点浪费时间,所以,针对这个问题,我用Node.js写了一个Copy文件的自动化小工具

全部源码

const fs =require('fs');
const path =require('path');

const srcDir =process.argv[2];
const destDir =process.argv[3];
const type =process.argv[4]
const copyNumber=process.argv[5]

let i=0;

while(i<copyNumber){
    i++;
    const num ='day'+(i+'').padStart(2,0);
    const srcPath =path.resolve(srcDir,num);
    const destPath =path.resolve(destDir,num);
    if(fs.existsSync(destPath))
        continue;
    fs.mkdir(destPath,(err)=>{
        if(!err)  console.log("文件创建成功开始拷贝:",num);

        const srcFiles=fs.readFileSync(srcPath)
        for(const file of srcFiles){
            if(file.endsWith(type)){
                const srcFile =path.resolve(srcPath,file)
                const destFile =path.resolve(destPath,file)
                fs.copyFileSync(srcFile,destFile)
                console.log(file,"拷贝成功");
            }}
    })

}

观察代码,可以发现,这里用到了fs模块以及path模块,procees.argv[?]表示用 node命名启动js文件后,后续跟的参数,scrDir是copy的源地址,destDir是copy的目的地址,type是文件类型,copyNumber是文件个数