0

I was using cpy with a globbing pattern to find and copy all the files in src/main/css and place them in ./dist.

However now I also have sub directories below src/main/css (For example src/main/css/margins/index.css) and cpy does not include these when copying the files.

Is there an API in Node (fs or path?) that handles this case, or anyone know of a handy package?

2 Answers 2

1

Try this.

const fs = require('fs');
const path = require('path');

var mkdir = function (dir) {
    // making directory without exception if exists
    try {
        fs.mkdirSync(dir, 0755);
    } catch (e) {
        if (e.code != "EEXIST") {
            throw e;
        }
    }
};

var copy = function (src, dest) {
    var readS = fs.createReadStream(src);
    var writeS = fs.createWriteStream(dest);
    readS.pipe(writeS);

    readS.on("end", function () {
        // Operation done
    });
};

var copyDir = function (src, dest) {
    mkdir(dest);
    var files = fs.readdirSync(src);
    for (var i = 0; i < files.length; i++) {
        var current = fs.lstatSync(path.join(src, files[i]));
        if (current.isDirectory()) {
            copyDir(path.join(src, files[i]), path.join(dest, files[i]));
        } else if (current.isSymbolicLink()) {
            var symlink = fs.readlinkSync(path.join(src, files[i]));
            fs.symlinkSync(symlink, path.join(dest, files[i]));
        } else {
            copy(path.join(src, files[i]), path.join(dest, files[i]));
        }
    }
};

copyDir('./src', './dest');

This piece of code is inspired from https://gist.github.com/tkihira/3014700. I have made some modifications in the original code to get it working as util.pump is obsolete now.

-1

I ended up using using copy-dir

require('copy-dir').sync(PLI.src.main.css, PLI.DIST);

If anyone has a way to do the same thing with the Node and avoiding dependencies please do tell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.