Skip to content

Instantly share code, notes, and snippets.

@AamuLumi
Created November 15, 2017 10:59
Show Gist options
  • Save AamuLumi/18771909904ac31fe934b32c1165f8ad to your computer and use it in GitHub Desktop.
Save AamuLumi/18771909904ac31fe934b32c1165f8ad to your computer and use it in GitHub Desktop.
Folder deep-copy in NodeJS (ES7+)
'use strict';
const fs = require('fs');
const path = require('path');
/**
* Create a folder and returns a Promise
* @param {String} folder
* @return {Promise}
*/
function makeFolder(folder) {
return new Promise((resolve, reject) => {
fs.mkdir(folder, (err) => {
if (err && err.errno !== -17) {
return reject(err);
}
resolve();
});
});
}
/**
* Call a function in a promise
* @param {Function} fn
* @param {*} args
* @return {Promise}
*/
function toPromise(fn, ...args) {
return new Promise((resolve, reject) => {
fn(...args, (err, data) => {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
const lstat = (...args) => toPromise(fs.lstat, ...args);
const readdir = (...args) => toPromise(fs.readdir, ...args);
const copyFile = (...args) => toPromise(fs.copyFile, ...args);
const readlink = (...args) => toPromise(fs.readlink, ...args);
const symlink = (...args) => toPromise(fs.symlink, ...args);
/**
* Copy a folder and returns a Promise
* @param {String} src
* @param {String} dest
*/
async function copyFolder(src, dest) {
await makeFolder(dest);
const files = await readdir(src);
for (let file of files) {
const current = await lstat(path.join(src, file));
if (current.isDirectory()) {
await copyFolder(path.join(src, file), path.join(dest, file));
} else if (current.isSymbolicLink()) {
let symlinkObj = await readlink(path.join(src, file));
await symlink(symlinkObj, path.join(dest, file));
} else {
await copyFile(path.join(src, file), path.join(dest, file));
}
}
}
function main() {
copyFolder('folderSrc', 'folderDest')
.catch(console.error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment