Skip to content

Instantly share code, notes, and snippets.

@mikaelvesavuori
Created April 1, 2018 19:48
Show Gist options
  • Save mikaelvesavuori/4e2769bab7a3abe0f10cd849b8bfce10 to your computer and use it in GitHub Desktop.
Save mikaelvesavuori/4e2769bab7a3abe0f10cd849b8bfce10 to your computer and use it in GitHub Desktop.
Node functions to copy files, folders (recursively), and rename files
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