Copy folder recursively in Node.js
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.js 8.5 there is a copyFileSync
function available which calls 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 ); } } ); }}
It looks like ncp and wrench both are no longer maintained. Probably the best option is to use fs-extra
The Developer of Wrench directs users to use fs-extra
as he has deprecated his library
copySync & moveSync both will copy and move folders even if they have files or subfolders and you can easily move or copy files using it
const fse = require('fs-extra');const srcDir = `path/to/file`;const destDir = `path/to/destination/directory`; // To copy a folder or file fse.copySync(srcDir, destDir, function (err) { if (err) { ^ console.error(err); |___{ overwrite: true } // add if you want to replace existing folder or file with same name } else { console.log("success!"); }});
OR
// To copy a folder or file fse.moveSync(srcDir, destDir, function (err) { if (err) { ^ console.error(err); |___{ overwrite: true } // add if you want to replace existing folder or file with same name } else { console.log("success!"); }});