Created
April 1, 2018 19:48
-
-
Save mikaelvesavuori/4e2769bab7a3abe0f10cd849b8bfce10 to your computer and use it in GitHub Desktop.
Node functions to copy files, folders (recursively), and rename files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
function copyFile(source, target) { | |
let targetFile = target; | |
if (fs.existsSync(target) && fs.lstatSync(target).isDirectory()) targetFile = path.join(target, path.basename(source)) | |
fs.writeFileSync(targetFile, fs.readFileSync(source)); | |
} | |
function copyFolderRecursive(source, target) { | |
if (!fs.existsSync(target)) { | |
fs.mkdirSync(target); | |
} | |
if (fs.lstatSync(source).isDirectory()) { | |
const files = fs.readdirSync(source); | |
files.forEach(file => { | |
const currentSource = path.join(source, file); | |
if (fs.lstatSync(currentSource).isDirectory()) { | |
copyFolderRecursive(currentSource, target); | |
} else { | |
copyFile(currentSource, target); | |
} | |
}); | |
} | |
} | |
function renameFile(originalFileName, newFileName) { | |
fs.rename(originalFileName, newFileName, function (err) { | |
if (err) console.log('Error when renaming file: ' + err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment