Jose Olivo
Jose Olivo

Reputation: 261

How to copy a file?

How to copy a file in Node.js?

Example

+ /old
|- image.png
+ /new

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

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!

Upvotes: 26

Views: 19759

Answers (4)

tomraithel
tomraithel

Reputation: 968

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!

Upvotes: 6

Oleg2tor
Oleg2tor

Reputation: 521

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

Upvotes: -3

Antony Hatchkins
Antony Hatchkins

Reputation: 33974

The preferred way currently:

oldFile.pipe(newFile);

Upvotes: 14

b_erb
b_erb

Reputation: 21241

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

Upvotes: 7

Related Questions