在node.js中复制文件的最快方法

本文翻译自:Fastest way to copy file in node.js

Project that I am working on (node.js) implies lots of operations with the file system (copying/reading/writing etc). 我正在处理的项目(node.js)暗示了文件系统的许多操作(复制/读取/写入等)。 I'd like to know which methods are the fastest, and I'd be happy to get an advice. 我想知道哪些方法是最快的,我很乐意得到建议。 Thanks. 谢谢。


#1楼

参考:https://stackoom.com/question/lO2z/在node-js中复制文件的最快方法


#2楼

This is a good way to copy a file in one line of code using streams: 这是使用流在一行代码中复制文件的好方法:

var fs = require('fs');

fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));

In node v8.5.0, copyFile was added 在节点v8.5.0中,添加了copyFile

const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});

#3楼

Same mechanism, but this adds error handling: 相同的机制,但这增加了错误处理:

function copyFile(source, target, cb) {
  var cbCalled = false;

  var rd = fs.createReadStream(source);
  rd.on("error", function(err) {
    done(err);
  });
  var wr = fs.createWriteStream(target);
  wr.on("error", function(err) {
    done(err);
  });
  wr.on("close", function(ex) {
    done();
  });
  rd.pipe(wr);

  function done(err) {
    if (!cbCalled) {
      cb(err);
      cbCalled = true;
    }
  }
}

#4楼

Well, usually it is good to avoid asynchronous file operations. 好吧,通常最好避免异步文件操作。 Here is the short (ie no error handling) sync example: 这是简短的(即没有错误处理)同步示例:

var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));

#5楼

Mike Schilling's solution with error handling with a short-cut for the error event handler. Mike Schilling的错误处理解决方案,带有错误事件处理程序的快捷方式。

function copyFile(source, target, cb) {
  var cbCalled = false;

  var rd = fs.createReadStream(source);
  rd.on("error", done);

  var wr = fs.createWriteStream(target);
  wr.on("error", done);
  wr.on("close", function(ex) {
    done();
  });
  rd.pipe(wr);

  function done(err) {
    if (!cbCalled) {
      cb(err);
      cbCalled = true;
    }
  }
}

#6楼

I was not able to get the createReadStream/createWriteStream method working for some reason, but using fs-extra npm module it worked right away. 由于某种原因,我无法使createReadStream/createWriteStream方法起作用,但是使用fs-extra npm模块可以立即起作用。 I am not sure of the performance difference though. 我不确定性能是否有所不同。

fs-extra fs-extra

npm install --save fs-extra

var fs = require('fs-extra');

fs.copySync(path.resolve(__dirname,'./init/xxx.json'), 'xxx.json');
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值