javascript 如何复制文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4980243/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:33:06  来源:igfitidea点击:

How to copy a file?

javascriptnode.js

提问by Jose Olivo

How to copy a file in Node.js?

如何在 Node.js 中复制文件?

Example

例子

+ /old
|- image.png
+ /new

I want to copy image1.png from 'old' to 'new' directory.

我想将 image1.png 从“旧”目录复制到“新”目录。

This doesn't work.

这不起作用。

newFile = fs.createWriteStream('./new/image2.png');     
oldFile = fs.createReadStream('./old/image1.png');

oldFile.addListener("data", function(chunk) {
  newFile.write(chunk);
})

oldFile.addListener("close",function() {
  newFile.end();
});

Thanks for reply!

谢谢你的回复!

回答by Antony Hatchkins

The preferred way currently:

目前首选的方式:

oldFile.pipe(newFile);

回答by b_erb

newFile.once('open', function(fd){
    require('util').pump(oldFile, newFile);
});     

回答by tomraithel

If you want to do this job syncronously, just read and then write the file directly:

如果你想同步完成这项工作,只需直接读取然后写入文件:

var copyFileSync = function(srcFile, destFile, encoding) {
  var content = fs.readFileSync(srcFile, encoding);
  fs.writeFileSync(destFile, content, encoding);
}

Of course, error handling and stuff is always a good idea!

当然,错误处理和其他东西总是一个好主意!

回答by Oleg2tor

fs.rename( './old/image1.png', './new/image2.png', function(err){
  if(err) console.log(err);
  console.log("moved");
});