如何复制文件?

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

+ /old |- image.png + /new 

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

这不起作用。

 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(); }); 

感谢您的回复!

目前的首选方式是:

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

如果你想同步做这个工作,直接读取然后直接写入文件:

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

当然,error handling和东西总是一个好主意!

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