Skip to content

Instantly share code, notes, and snippets.

@piboistudios
Created July 25, 2019 17:09
Show Gist options
  • Save piboistudios/e9312b0b82d0c20e21d7f5da3f826d13 to your computer and use it in GitHub Desktop.
Save piboistudios/e9312b0b82d0c20e21d7f5da3f826d13 to your computer and use it in GitHub Desktop.
Recursively Copy a Directory to another location
/**
* Moves files from one location to another, recursively traverses subdirectories.
* example usage: move-dir ./a ./b
*/
const fs = require('fs');
const fromDir = process.argv[2];
const bluebird = require('bluebird');
const chalk = require('chalk');
const toDir = process.argv[3];
console.log({ fromDir, toDir });
const exists = (...args) => {
try {
args.forEach(fs.accessSync);
return true;
} catch (err) {
return false;
}
}
(async () => {
const read = bluebird.promisify(fs.readFile);
const write = bluebird.promisify(fs.writeFile);
const stat = bluebird.promisify(fs.stat);
const readdir = bluebird.promisify(fs.readdir);
if (exists(fromDir)) {
try {
!exists(toDir) && fs.mkdirSync(toDir);
} catch (err) {
console.error(err);
return;
}
const promises = [];
const processPath = async _path => {
const path = _path !== fromDir ? `${fromDir}${fromDir[fromDir.length - 1] === '/' ? '' : '/'}${_path}` : _path;
const stats = await stat(path);
if (stats.isDirectory()) {
const paths = await readdir(path);
if (path !== fromDir) {
try {
const subDir = `${toDir}${toDir[toDir.length - 1] === '/' ? '' : '/'}${_path}`;
!exists(subDir) && fs.mkdirSync(subDir);
} catch (err) {
console.error(err);
return;
}
}
(path !== fromDir ? paths.map(subPath => `${_path}/${subPath}`) : paths).forEach(processPath);
} else {
promises.push(read(path).then(contents => {
const movedFileName = `${toDir}${toDir[toDir.length - 1] === '/' ? '' : '/'}${_path}`;
promises.push(write(movedFileName, contents).then(() => {
console.log(`Successfully wrote ${movedFileName}.`);
}).catch(err => {
console.error(err);
}))
}).catch(err => {
console.error(error);
}));
}
}
await processPath(fromDir);
await bluebird.all(promises);
console.log("Done.");
} else {
console.log(chalk.red('The given path', fromDir, 'does not exist'));
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment