Nodachisoft Nodachisoft logo, Katana Sword Icon
  
@Amaji✎ Update December-16-2021

How to copy directory recursively in javascript on nodejs.

How to copy directory recursively in javascript on nodejs.

Summury Of Article

Describes How to copy directory recursively with javascript on nodejs , with sample code that can be copied and pasted.

In javascript running on nodejs, there are times when I want to copy the entire specified directory to another location.

So, here is the code that does this recursively, using only the standard functions of nodejs.

Note that this blog is written in React-based (Gatsby), and When I want to create a new blog article, I use the npm run xxxx command to create a copy of the template folder, and this code is also used to create that copy!

Code

The following example defines a function CopyFilesRecursively to recursively copy a specified path (directory) to a target location, and calls it as a test.

 
copyfiles_recursively.js
/**
 * serach files and directories recursively.
 *  Option: you can limit search path depth.
 * @param {string} targetpath search base path
 * @param {number} depth recursive depth. default = no depth limit
 * @returns list of { path:absolute path, isDir:is directory } of files and dirs in targetpath
 */
var GetFilelistRecursively2 = ((targetpath, depth = -1) => {
    let result = [];
    let dirs = fs.readdirSync(targetpath);
    dirs.forEach(file => {
        let filepath = targetpath + "/" + file;
        let isDir = fs.lstatSync(filepath).isDirectory();
        result.push({path:filepath, isDir:isDir });
        if ( isDir ) {
            if ( depth == 0 ) return result;
            result = result.concat( GetFilelistRecursively2(filepath, depth - 1));
        }
    });
    return result;
});

/**
 * Recursively copies folders and files under the specified path with the same structure.
 * If the destination directory does not exist, a folder will be created and copied into it.
 * In case of insufficient permissions or insufficient capacity, it will detect an exception and stop.
 * @param {string} srcpath copy from the path
 * @param {string} destpath copy to the path
 */
var CopyFilesRecursively = ((srcpath, destpath) => {
    if ( !fs.existsSync(destpath) ) {
        fs.mkdirSync(destpath,{ recursive: true } );
    }
    let targetList = GetFilelistRecursively2( srcpath );
    targetList.forEach( node => {
        let newpath = destpath + node.path.substring(srcpath.length);
        if ( node.isDir) {
            if ( !fs.existsSync(destpath) ) fs.mkdirSync(newpath);
        } else {
            fs.copyFile(node.path, newpath, err => {if (err) throw err});
        }
    });
});

// For example:
CopyFilesRecursively("C:/testdir", "C:/testdir2");

Two functions, GetFilelistRecursively2 and CopyFilesRecursively, are defined. The latter, CopyFilesRecursively, is called when copying a folder.

In the code, the list of source files and folders is recursively retrieved, and then the structure is copied to the specified destination path.

Note that GetFilelistRecursively2 is a function to get a list of files and folders, and GetFilelistRecursively2 is a function to get a list of files and folders. It uses the one created in the other article here.

If you are interested, please refer to that article as well.

Websites and references that were very helpful.

Page History

date modification
none
 
 
Message sent

Thank you for your message.

Something error has occured!

Sorry. The Error has occurred.We apologize for the inconvenience.Please try again in a few minutes or contact us via DM below.

Twitter:@NodachiSoft_eng
Name:
 
Replay To:
 
Message:
 
Back
Check the content!

Send the following information to us. If you are happy with your submission, please click "Send". If you want to modify it, please click "Back".

Name:
 
Reply To:
 
Message:
 
Enter a confirmation key to make sure that you are not operating from a Robot.
Confirmation Key is 95
Back
 / 
Go to Confirmation
Entry fields
Go to Confirmation

There are 5 articles that may be relevant!

How to pass arguments to npm run script

How to pass arguments to npm run script

#Nodejs#Javascript✎ 2021-12-16
Describe how to pass argument to npm run script.
Table Of Contents
How to copy directory recursively in javascript on nodejs.
How to copy directory recursively in javascript on nodejs.
Summury Of Article
Summury Of Article
Code
Code
Websites and references that were very helpful.
Websites and references that were very helpful.
Page History
Page History
Nodachisoft © 2021