node.jsdirectorycopyrsyncfs-extra

NodeJS - How to copy one folder to another, overwriting only files that differ?


The question:

How to copy one folder to another in NodeJS, overwriting only files that differ?


About fs-extra "copy" method:

It seems that the copy method from fs-extra does not have the option to skip identical files (that have not undergone any modification).

There is the overwrite option, but it only gives you the choice to overwrite in all cases, even when the files are identical, or to not overwrite, even if the files differ.


Solution

  • I created an open source nodejs library, called Reflect - https://github.com/alumna/reflect

    I was unhappy with the fact that both libraries I mentioned earlier depends on rsync command, which is not a multi-platform decision, since Windows doesn't provide rsync natively.

    I made Reflect in pure javascript to solve this, with no dependency on rsync or any other library, making it suitable for all operational systems.

    Just a note: Reflect compares files similarly to rsync and syncs only the difference between two folders, completely avoiding the copy of non-modified files (or modified but still identical files), but it is still not suitable for projects with large files, since it copies the whole file when it differs.


    Install

    $ npm install @alumna/reflect
    

    Usage

    import reflect from '@alumna/reflect';
    
    let { res, err } = await reflect({
    
        src: 'src/',
        
        dest: 'dest/',
        
        // (OPTIONAL) Default to 'true'
        recursive: true,
        
        // (OPTIONAL) Default to 'true'
        // Delete in dest the non-existent files in src
        delete: true,
        
        // (OPTIONAL)
        // Array with files and folders not to reflect
        exclude: [ "skip-this-file.txt", "skip/this/directory" ]
        
    });
    
    if ( err )
        console.error( err )
    
    else
        console.log( res ) // Directory "src/" reflected to "dest/"