Skip to content

Instantly share code, notes, and snippets.

@piboistudios
Created July 25, 2019 17:09

Revisions

  1. piboistudios created this gist Jul 25, 2019.
    76 changes: 76 additions & 0 deletions copy-directory-to.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    /**
    * 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'));
    }
    })()