Copy folder recursively in Node.js

前端 未结 25 1970
隐瞒了意图╮
隐瞒了意图╮ 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:32

    This is how I did it:

    let fs = require('fs');
    let path = require('path');
    

    Then:

    let filePath = // Your file path
    
    let fileList = []
        var walkSync = function(filePath, filelist)
        {
            let files = fs.readdirSync(filePath);
            filelist = filelist || [];
            files.forEach(function(file)
            {
                if (fs.statSync(path.join(filePath, file)).isDirectory())
                {
                    filelist = walkSync(path.join(filePath, file), filelist);
                }
                else
                {
                    filelist.push(path.join(filePath, file));
                }
            });
    
            // Ignore hidden files
            filelist = filelist.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item));
    
            return filelist;
        };
    

    Then call the method:

    This.walkSync(filePath, fileList)
    

提交回复
热议问题