简体   繁体   English

使用nodejs复制大量文件?

[英]Copying large amount of files with nodejs?

I have to copy a large amount of files (like 25000) asynchronously. 我必须异步复制大量文件(例如25000)。 I'm using this library: https://github.com/stephenmathieson/node-cp . 我正在使用此库: https : //github.com/stephenmathieson/node-cp

This is my code: 这是我的代码:

         for(var i = 0; i < 25000; i++){
            cp(origin[i], dest[i], function(err){
              console.log("successfully copied")
            })
         }

It completes the loop but it doens't copy every item. 它完成了循环,但不会复制所有项目。 The "Successfully copied" is called between 6000 and 8000 times. “成功复制”被调用6000至8000次。 After that it doesn't copy anymore. 之后,它将不再复制。 It has something to do with the memory or a limit for async tasks? 它与内存有关还是对异步任务有限制?

Any help would be appreciated! 任何帮助,将不胜感激!

The copy function takes a callback which is usually a good clue that it's asynchronous. 复制函数接受一个回调,这通常是异步的一个很好的线索。 That means that the for loop will continue to run even though the copy hasn't completed, meaning you just queued up 25,000 copy operations! 这意味着即使复制尚未完成,for循环仍将继续运行,这意味着您仅排队25,000个复制操作!

There's a few ways to solve this but among the most common is using the async module. 有几种方法可以解决此问题,但最常见的方法是使用异步模块。

var async = require('async');
async.forEachOf(origin, function (file, i, callback) {
    cp(file, dest[i], function(err){
        callback();
    });
})

This won't proceed to the next iteration of the loop until callback is called. callback之前,不会进行循环的下一个迭代。

you can copy async with this, 您可以与此复制异步,

var fs = require('fs-extra')

fs.copy('/tmp/myfile', '/tmp/mynewfile', function (err) {
  if (err) return console.error(err)
  console.log("success!")
}) // copies file 

fs.copy('/tmp/mydir', '/tmp/mynewdir', function (err) {
  if (err) return console.error(err)
  console.log('success!')
}) // copies directory, even if it has subdirectories or file

info => https://www.npmjs.com/package/fs-extra 信息=> https://www.npmjs.com/package/fs-extra

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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