26

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!

Jose Olivo
  • 261
  • 1
  • 3
  • 4

4 Answers4

14

The preferred way currently:

oldFile.pipe(newFile);
Antony Hatchkins
  • 31,947
  • 10
  • 111
  • 111
7
newFile.once('open', function(fd){
    require('util').pump(oldFile, newFile);
});     
b_erb
  • 20,932
  • 8
  • 55
  • 64
  • 1
    Does this work for you? I use Node v0.4.0 and `newFile` has zero KB. – Baggz Feb 14 '11 at 13:17
  • 3
    You must wait for the 'open' event of the file to be written. (I added this now). – b_erb Feb 14 '11 at 14:38
  • a simple `require('util').pump(oldFile, newFile);` worked for me (not waiting for the open event) – Drew LeSueur Feb 22 '12 at 14:02
  • `pump` status was like [that](https://groups.google.com/forum/?fromgroups#!topic/nodejs/FwdDQvAf4xM): 'You can expect `util.pump` to go away in the future' as early as Apr'11; it is currently marked 'Experimental' in the docs. See also http://stackoverflow.com/questions/9726507/what-is-the-difference-between-util-pumpstreama-streamb-and-streama-pipestre – Antony Hatchkins Jul 04 '12 at 18:56
  • 1
    You're very outdated, use `pipe`!! See Antony Hatchkins answer. – Alba Mendez Oct 21 '12 at 10:46
  • **But what about the `mode`, `permissions`, `owner` and `timestamps`?** They're lost. Lost in time. Like my cat. – Alba Mendez Oct 21 '12 at 10:49
6

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!

tomraithel
  • 958
  • 2
  • 13
  • 22
-3
fs.rename( './old/image1.png', './new/image2.png', function(err){
  if(err) console.log(err);
  console.log("moved");
});
Oleg2tor
  • 531
  • 1
  • 8
  • 18