简体   繁体   中英

Node.js copy files from several directories to one directory

How to copy files from several directories to one directory with Node.js. Provided that there are several directories in one directory.

I have a solution

var fs = require('fs');
var ncp = require('ncp').ncp;
ncp.limit = 16;
fs.readdir(__dirname, function(err, files) {
    for (var i = 0; i < files.length; i++) {
        ncp(files[i], 'C:/Users/User/Desktop/output', function(err) {
            if (err) {
                return console.error(err);
            }
            console.log('done!');
        });
    }
});

But it may be possible to make it better?

If you have a large number of files and folders to copy, you most likely will get the following error message

Error: EMFILE, too many open files

To solve this problem I recommend using modules graceful-fs and graceful-ncp instead fs and ncp

Install this modules

npm install graceful-fs graceful-ncp

and use in code

var fs = require('graceful-fs');
var ncp = require('graceful-ncp').ncp;
ncp.limit = 16;
fs.readdir(__dirname, function(err, files) {
    for (var i = 0; i < files.length; i++) {
        ncp(files[i], 'C:/path/to/output/folder', function(err) {
            if (err) {
                return console.error(err);
            }
            console.log('done!');
        });
    }
});

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