博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在node.js中复制文件的最快方法
阅读量:2290 次
发布时间:2019-05-09

本文共 2299 字,大约阅读时间需要 7 分钟。

本文翻译自:

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楼

参考:


#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'));

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. 我不确定性能是否有所不同。

npm install --save fs-extra

var fs = require('fs-extra');fs.copySync(path.resolve(__dirname,'./init/xxx.json'), 'xxx.json');

转载地址:http://jvcnb.baihongyu.com/

你可能感兴趣的文章