November 14, 2014

Advanced file system manipulations using node.js scripting

Below you can find several functions that will help you to manage your files in more advanced way:

1. Synchronously create directory even if its parent directories don’t exist : createPathSync(‘a/b/c/d/e’);
2. Synchronously copy file: copyFileSync( source, target );
3. Synchronously copy directory with its content: copyFolderRecursiveSync( source, target );
4. Synchronously delete directory with its content: deleteFolderRecursiveSync(target);
5. Asynchronously zip folder: makeZip(source, target, zipName, callback);

first of all lets define dependencies:
archiver you only need to use zip functionality.

var fs = require('fs');
var path = require('path');
var archiver = require('archiver');    //npm install archiver
1. Synchronously create directory even if its parent directories don’t exist : createPathSync(‘a/b/c/d/e’);

function createPathSync(dirPath, mode, fullPath) { //usage: createPathSync('a/b/c/d', [mode]);
    if (typeof fullPath == 'undefined') fullPath = dirPath;    //initialization
    try {
        //try to make dir
        fs.mkdirSync(dirPath, mode);
        //if succeeded go recursive or finish
        if (!fs.existsSync(fullPath)) createPathSync(fullPath, mode, fullPath);
    } catch (err) {
        createPathSync(path.dirname(dirPath), mode, fullPath);
    }
}
2. Synchronously copy file: copyFileSync( source, target );

function copyFileSync(source, target) {
    var targetFile = target;
    if (fs.existsSync(target)) {
        if (fs.lstatSync(target).isDirectory()) {
            targetFile = path.join(target, path.basename(source));
        }
    }
    fs.createReadStream(source).pipe(fs.createWriteStream(targetFile));
}
3. Synchronously copy directory with its content: copyFolderRecursiveSync( source, target );

function copyFolderRecursiveSync(source, target) {
    var files = [];
    if (!fs.existsSync(target)) {    //assure that target path exists
        createPathSync(target);
    }
    if (fs.lstatSync(source).isDirectory()) {
        files = fs.readdirSync(source);
        files.forEach(function (file, index) {
            var curSource = path.join(source, file);
            var curTarget = path.join(target, file);
            if (fs.lstatSync(curSource).isDirectory()) {
                copyFolderRecursiveSync(curSource, curTarget);
            } else {
                //console.log(curSource+'       '+ curTarget);
                copyFileSync(curSource, curTarget);
            }
        });
    }
}
4. Synchronously delete directory with its content: deleteFolderRecursiveSync(target);

function deleteFolderRecursiveSync(path) {
    if (fs.existsSync(path)) {
        fs.readdirSync(path).forEach(function (file, index) {
            var curPath = path + "/" + file;
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursiveSync(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};
5. Asynchronously zip folder: makeZip(source, target, zipName, callback);

function makeZip(from, to, zipName, callback) {
    var zipArchive = archiver('zip');
    var zipOutput = fs.createWriteStream(to + '/' + zipName);
    zipOutput.on('close', function () {
        console.log('zipping done: ', to + '/' + zipName);
        callback();
    });
    zipArchive.pipe(zipOutput);
    zipArchive.bulk([{ src: ['**/*'], cwd: from, expand: true }]);
    zipArchive.finalize(function (err, bytes) {
        if (err) throw err;
        console.log('done:', base, bytes);
    });
}

No comments:

Post a Comment