Javascript 在 node.js 中复制文件的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11293857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to copy file in node.js
提问by bonbonez
Project that I am working on (node.js) implies lots of operations with the file system (copying/reading/writing etc). I'd like to know which methods are the fastest, and I'd be happy to get an advice. Thanks.
我正在处理的项目 (node.js) 意味着对文件系统进行大量操作(复制/读取/写入等)。我想知道哪种方法最快,我很乐意得到建议。谢谢。
回答by Miguel Sanchez Gonzalez
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
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');
});
回答by Mike Schilling
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;
}
}
}
回答by Timmerz
I was not able to get the createReadStream/createWriteStream
method working for some reason, but using fs-extra
npm module it worked right away. I am not sure of the performance difference though.
createReadStream/createWriteStream
由于某种原因,我无法使该方法起作用,但是使用fs-extra
npm 模块它立即起作用了。虽然我不确定性能差异。
npm install --save fs-extra
npm install --save fs-extra
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./init/xxx.json'), 'xxx.json');
回答by Mikhail
Since Node.js 8.5.0 we have new fs.copyFileand fs.copyFileSyncmethods.
从 Node.js 8.5.0 开始,我们有了新的fs.copyFile和fs.copyFileSync方法。
Usage Example:
用法示例:
var 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');
});
回答by benweet
Fast to write and convenient to use, with promise and error management.
编写快速,使用方便,具有承诺和错误管理。
function copyFile(source, target) {
var rd = fs.createReadStream(source);
var wr = fs.createWriteStream(target);
return new Promise(function(resolve, reject) {
rd.on('error', reject);
wr.on('error', reject);
wr.on('finish', resolve);
rd.pipe(wr);
}).catch(function(error) {
rd.destroy();
wr.end();
throw error;
});
}
Same with async/await syntax:
与 async/await 语法相同:
async function copyFile(source, target) {
var rd = fs.createReadStream(source);
var wr = fs.createWriteStream(target);
try {
return await new Promise(function(resolve, reject) {
rd.on('error', reject);
wr.on('error', reject);
wr.on('finish', resolve);
rd.pipe(wr);
});
} catch (error) {
rd.destroy();
wr.end();
throw error;
}
}
回答by Tester
Well, usually it is good to avoid asynchronous file operations. Here is the short (i.e. no error handling) sync example:
嗯,通常最好避免异步文件操作。这是简短的(即无错误处理)同步示例:
var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));
回答by Jens Hauke
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;
}
}
}
回答by Andrew Childs
If you don't care about it being async, and aren't copying gigabyte-sized files, and would rather not add another dependency just for a single function:
如果您不关心它是异步的,并且不复制千兆字节大小的文件,并且宁愿不为单个函数添加另一个依赖项:
function copySync(src, dest) {
var data = fs.readFileSync(src);
fs.writeFileSync(dest, data);
}
回答by AYO O.
const fs = require("fs");
fs.copyFileSync("filepath1", "filepath2"); //fs.copyFileSync("file1.txt", "file2.txt");
This is what I personally use to copy a file and replace another file using node.js :)
这是我个人用来复制文件并使用 node.js 替换另一个文件的方法:)
回答by chpio
For fast copies you should use the fs.constants.COPYFILE_FICLONE
flag. It allows (for filesystems that support this) to not actually copy the content of the file. Just a new file entry is created, but it points to a Copy-on-Write"clone" of the source file.
对于快速复制,您应该使用该fs.constants.COPYFILE_FICLONE
标志。它允许(对于支持此功能的文件系统)实际上不复制文件的内容。只创建了一个新文件条目,但它指向源文件的写时复制“克隆”。
To do nothing/less is the fastest way of doing something ;)
什么都不做/少做是最快的做事方式;)
https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_flags_callback
https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_flags_callback
let fs = require("fs");
fs.copyFile(
"source.txt",
"destination.txt",
fs.constants.COPYFILE_FICLONE,
(err) => {
if (err) {
// TODO: handle error
console.log("error");
}
console.log("success");
}
);
Using promises instead:
改用承诺:
let fs = require("fs");
let util = require("util");
let copyFile = util.promisify(fs.copyFile);
copyFile(
"source.txt",
"destination.txt",
fs.constants.COPYFILE_FICLONE
)
.catch(() => console.log("error"))
.then(() => console.log("success"));