简体   繁体   中英

How to copy data from one directory to another using nodejs fs?

trying to copy parent content to child its throwing error and going into catch , any idea what i am doing wrong here.

main.js

const fs = require('fs-extra');
const copyDirectories = function(data) {

        let destination = 'services/test2/tmp';
        let source = 'services/test2';
        fs.copy(source, destination)
        .then(() => console.log('Copy completed!'))
        .catch( err => {
            console.log('An error occured while copying the folder.')
            return console.error(err)
        })
     }

The problem is that copying all contents of a directory into a subdirectory is a recursive call. Assume that I try to copy the contents of directory a/ into a/b/ , then the files a/b/* would be copied to a/b/b/* which then must be copied to a/b/b/b/* etc.

One of the ways to solve this issue is to first copy the contents in a temporary directory. Then, when copying is finished, move the file back into the structure.

This answer assumes the following file structure:

$ tree -F services
services
└── test2/
    ├── foo.txt
    └── tmp/

2 directories, 1 file
const fs = require('fs-extra');

const copyDirectories = async function(data) {
    const source = "services/test2";
    const destination = "services/test2/tmp";
    const tmp = "tmp-a11b23bsf3"; // <- assume randomized to not conflict

    await fs.mkdir(tmp);
    await fs.copy(source, tmp);
    await fs.move(tmp, destination, {overwrite: true});
};
$ tree -F services
services
└── test2/
    ├── foo.txt
    └── tmp/
        ├── foo.txt
        └── tmp/

3 directories, 2 files

Note that this does require that provided temporary directory does not conflict with existing directories.

You can avoid possible conflicts by first retrieving a list of files/directories in the current directory. Then randomize a file name (using an uuid for example), check if it is the list, if it is randomize again. Finally save the non-conflicting name in a variable and create the directory.

Assuming the creation of the initial directory succeeds you can now copy the files over. Then move the folder to the original destination, optionally renaming it in the processes. If an error is thrown in this process you might want to consider removing the created temporary directory and its contents before throwing an exception or returning from the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM