Copy folder recursively in node.js


Question

Is there an easier way to copy a folder and all its content without manually doing a sequence of fs.readir , fs.readfile, fs.writefile recursively ?

Just wondering if i'm missing a function which would ideally work like this

fs.copy("/path/to/source/folder","/path/to/destination/folder");
1
119
12/9/2012 9:17:29 AM

Accepted Answer

You can use ncp module. I think this is what you need

101
12/9/2012 9:25:20 AM

This is my approach to solve this problem without any extra modules. Just using the built-in fs and path modules.

Note: This does use the read / write functions of fs so it does not copy any meta data (time of creation etc.). As of node 8.5 there is a copyFileSync functions available which call the OS copy functions and therefore also copies meta data. I did not test them yet, but it should work to just replace them. (See https://nodejs.org/api/fs.html#fs_fs_copyfilesync_src_dest_flags)

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

function copyFileSync( source, target ) {

    var targetFile = target;

    //if target is a directory a new file with the same name will be created
    if ( fs.existsSync( target ) ) {
        if ( fs.lstatSync( target ).isDirectory() ) {
            targetFile = path.join( target, path.basename( source ) );
        }
    }

    fs.writeFileSync(targetFile, fs.readFileSync(source));
}

function copyFolderRecursiveSync( source, target ) {
    var files = [];

    //check if folder needs to be created or integrated
    var targetFolder = path.join( target, path.basename( source ) );
    if ( !fs.existsSync( targetFolder ) ) {
        fs.mkdirSync( targetFolder );
    }

    //copy
    if ( fs.lstatSync( source ).isDirectory() ) {
        files = fs.readdirSync( source );
        files.forEach( function ( file ) {
            var curSource = path.join( source, file );
            if ( fs.lstatSync( curSource ).isDirectory() ) {
                copyFolderRecursiveSync( curSource, targetFolder );
            } else {
                copyFileSync( curSource, targetFolder );
            }
        } );
    }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon