Skip to content

Instantly share code, notes, and snippets.

@GUIEEN
Last active January 3, 2019 19:34
Show Gist options
  • Select an option

  • Save GUIEEN/18094f4aea9e4a269aab9182a48d86d1 to your computer and use it in GitHub Desktop.

Select an option

Save GUIEEN/18094f4aea9e4a269aab9182a48d86d1 to your computer and use it in GitHub Desktop.
copy folder recursively
import fs from 'fs'
import path from 'path'
function copyFileSync (source, target) {
let targetFile = target
// if target is a directory a new file with the same name will be created
if (fs.existsSync(target)) {
if (fs.lstatSync(target).isDirectory()) {
targetFile = path.join(target, path.basename(source))
}
}
fs.writeFileSync(targetFile, fs.readFileSync(source))
}
function copyFolderRecursiveSync (source, target) {
if (!fs.lstatSync(dirSource).isDirectory()) return
let files = []
let targetFolder = path.join(target, path.basename(dirSource))
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder)
}
files = fs.readdirSync(dirSource)
files.forEach(function (file) {
let curSource = path.join(dirSource, file)
if (fs.lstatSync(curSource).isDirectory()) {
copyFolderRecursiveSync(curSource, targetFolder)
} else {
copyFileSync(curSource, targetFolder)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment