美文网首页
nodejs复制文件夹到新目录

nodejs复制文件夹到新目录

作者: GuitarHusky | 来源:发表于2023-12-04 17:16 被阅读0次
    1.复制源文件夹内容到新文件夹
    //获取node中path目录模块及fs文件模块
    const path = require('path')  
    const fs = require('fs')
    
    // 配置原文件目录路径,及要复制到的新文件目录路径
    // 此处注意是双斜杠,因为单斜杠会被转移报错
    let oldFilePath = 'C:\\Users\\testAPath'
    let newFilePath = 'C:\\Users\\testBPath'
    
    // 判断要复制过去的文件夹新目录是否存在,不存在则创建
    if (!fs.existsSync(newFilePath)) {
        fs.mkdir(newFilePath, err => {
            // console.log(err)
        })
    }
    
    function copyFilesToNewPath(oldFilePath, newFilePath) {
        //读取原文件夹下的文件
        fs.readdir(oldFilePath, { withFileTypes: true }, (err, files) => {
            for (let file of files) {
                //判断当前文件是否是文件夹,非文件夹则直接复制
                if (!file.isDirectory()) {
                    //获取原文件中的文件名路径
                    const oldFile = path.resolve(oldFilePath, file.name)
                    //组成新文件中的文件名路径
                    const newFile = path.resolve(newFilePath, file.name)
                    //将文件从旧文件夹复制到新文件夹中
                    fs.copyFileSync(oldFile, newFile)
                } else {
                    //如果是文件夹就递归传入子项的目录名
                    const newDirPath = path.resolve(newFilePath, file.name)
                    const oldDirPath = path.resolve(oldFilePath, file.name)
                    //在新文件夹中创建子项文件夹
                    fs.mkdir(newDirPath, (err) => {
    
                    })
                    copyFilesToNewPath(oldDirPath, newDirPath)
                }
            }
        })
    }
    
    //传入路径  执行复制移动
    copyFilesToNewPath(oldFilePath, newFilePath)
    
    2.将nodejs脚本编译为windows下的exe文件,后续可直接双击执行
    # 安装pkg
    npm install -g pkg
    # 使用pkg打包, 该命令会同时编译 linux, win, mac 版的exe
    pkg copyMove.js
    # 只打包win版
    pkg -t win copyMove.js
    

    相关文章

      网友评论

          本文标题:nodejs复制文件夹到新目录

          本文链接:https://www.haomeiwen.com/subject/vmhrgdtx.html