NodeJS 復(fù)制任意目錄下的文件到另一目錄

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

const sourceDir = process.argv[2]
const targetDir = process.argv[3]


const isExist = (path) => { // 判斷文件夾是否存在, 不存在創(chuàng)建一個
  if (!fs.existsSync(path)) {
    fs.mkdirSync(path)
  }
}

isExist(targetDir)

const copyFile = (sourcePath, targetPath) => {
  const sourceFile = fs.readdirSync(sourcePath, { withFileTypes: true })

  sourceFile.forEach(file => {
    const newSourcePath = path.resolve(sourcePath, file.name)
    const newTargetPath = path.resolve(targetPath, file.name)
    if (file.isDirectory()) {
      isExist(newTargetPath)
      copyFile(newSourcePath, newTargetPath)
    }
    if (file.name.endsWith('.mp4')) { // 需要復(fù)制其他的格式的文件修改 .mp4 既可
      fs.copyFileSync(newSourcePath, newTargetPath)
    }
  })
}

copyFile(sourceDir, targetDir)

使用說明: 代碼保存到文件, 需要復(fù)制什么格式的文件, 把代碼中的 .mp4 修改成對應(yīng)的格式,最后使用 node 運(yùn)行代碼, 傳入需要復(fù)制的文件路徑和復(fù)制到的目標(biāo)路徑即可.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容