Copy folder recursively in Node.js

前端 未结 25 1809
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 07:44

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

相关标签:
25条回答
  • 2020-12-04 08:06

    fs-extra worked for me when ncp and wrench fell short:

    https://www.npmjs.com/package/fs-extra

    0 讨论(0)
  • 2020-12-04 08:08

    Be careful when picking your package. Some packages like copy-dir does not support copying large files more than 0X1FFFFFE8 characters (about 537 MB) long.

    It will throw some error like:

    buffer.js:630 Uncaught Error: Cannot create a string longer than 0x1fffffe8 characters

    I have experienced something like this in one of my projects. Ultimately, I had to change the package I was using and adjust a lot of code. I would say that this is not a very pleasant experience.

    If multiple source and multiple destination copies are desired, you can use better-copy and write something like this:

    // Copy from multiple source into a directory
    bCopy(['/path/to/your/folder1', '/path/to/some/file.txt'], '/path/to/destination/folder');
    

    Or even:

    // Copy from multiple source into multiple destination
    bCopy(['/path/to/your/folder1', '/path/to/some/file.txt'], ['/path/to/destination/folder', '/path/to/another/folder']);
    
    0 讨论(0)
  • 2020-12-04 08:09

    This is how I would do it personally:

    function copyFolderSync(from, to) {
        fs.mkdirSync(to);
        fs.readdirSync(from).forEach(element => {
            if (fs.lstatSync(path.join(from, element)).isFile()) {
                fs.copyFileSync(path.join(from, element), path.join(to, element));
            } else {
                copyFolderSync(path.join(from, element), path.join(to, element));
            }
        });
    }
    

    It works for folders and files.

    0 讨论(0)
  • 2020-12-04 08:09

    If you want to copy all contents of source directory recursively then you need to pass recursive option as true and try catch is documented way by fs-extra for sync

    As fs-extra is complete replacement of fs so you don't need to import the base module

    const fs = require('fs-extra');
    let sourceDir = '/tmp/src_dir';
    let destDir = '/tmp/dest_dir';
    try {
      fs.copySync(sourceDir, destDir, { recursive: true })
      console.log('success!')
    } catch (err) {
      console.error(err)
    }
    
    
    0 讨论(0)
  • 2020-12-04 08:09

    The easiest approach for this problem is to use only the 'fs' and 'Path' module and some logic...

    All files in the root folder copy with the new name if you want to just set the version number, i.e., " var v = 'Your Directory Name'"

    In the file name prefix with content added with the file name.

    var fs = require('fs-extra');
    var path = require('path');
    
    var c = 0;
    var i = 0;
    var v = "1.0.2";
    var copyCounter = 0;
    var directoryCounter = 0;
    var directoryMakerCounter = 0;
    var recursionCounter = -1;
    var Flag = false;
    var directoryPath = [];
    var directoryName = [];
    var directoryFileName = [];
    var fileName;
    var directoryNameStorer;
    var dc = 0;
    var route;
    
    if (!fs.existsSync(v)) {
        fs.mkdirSync(v);
    }
    
    var basePath = path.join(__dirname, v);
    
    
    function walk(dir) {
    
        fs.readdir(dir, function(err, items) {
    
            items.forEach(function(file) {
    
                file = path.resolve(dir, file);
    
                fs.stat(file, function(err, stat) {
    
                    if(stat && stat.isDirectory()) {
                        directoryNameStorer = path.basename(file);
                        route = file;
                        route = route.replace("gd", v);
    
                        directoryFileName[directoryCounter] = route;
                        directoryPath[directoryCounter] = file;
                        directoryName[directoryCounter] = directoryNameStorer;
    
                        directoryCounter++;
                        dc++;
    
                        if (!fs.existsSync(basePath + "/" + directoryName[directoryMakerCounter])) {
                            fs.mkdirSync(directoryFileName[directoryMakerCounter]);
                            directoryMakerCounter++;
                        }
                    }
                    else {
                        fileName = path.basename(file);
                        if(recursionCounter >= 0) {
                            fs.copyFileSync(file, directoryFileName[recursionCounter] + "/" + v + "_" + fileName, err => {
                                if(err) return console.error(err);
                            });
                            copyCounter++;
                        }
                        else {
                            fs.copyFileSync(file, v + "/" + v + "_" + fileName, err => {
                                if(err) return console.error(err);
                            });
                            copyCounter++;
                        }
                    }
                    if(copyCounter + dc == items.length && directoryCounter > 0 && recursionCounter < directoryMakerCounter-1) {
                        console.log("COPY COUNTER:             " + copyCounter);
                        console.log("DC COUNTER:               " + dc);
                        recursionCounter++;
                        dc = 0;
                        copyCounter = 0;
                        console.log("ITEM DOT LENGTH:          " + items.length);
                        console.log("RECURSION COUNTER:        " + recursionCounter);
                        console.log("DIRECOTRY MAKER COUNTER:  " + directoryMakerCounter);
                        console.log(": START RECURSION:        " + directoryPath[recursionCounter]);
                        walk(directoryPath[recursionCounter]); //recursive call to copy sub-folder
                    }
                })
            })
        });
    }
    
    walk('./gd', function(err, data) { // Just pass the root directory which you want to copy
        if(err)
            throw err;
        console.log("done");
    })
    
    0 讨论(0)
  • 2020-12-04 08:10

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

    0 讨论(0)
提交回复
热议问题