How to copy a file?

后端 未结 4 1843
说谎
说谎 2020-12-29 04:00

How to copy a file in Node.js?

Example

+ /old
|- image.png
+ /new

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

相关标签:
4条回答
  • 2020-12-29 04:20
    newFile.once('open', function(fd){
        require('util').pump(oldFile, newFile);
    });     
    
    0 讨论(0)
  • 2020-12-29 04:22

    The preferred way currently:

    oldFile.pipe(newFile);
    
    0 讨论(0)
  • 2020-12-29 04:35
    fs.rename( './old/image1.png', './new/image2.png', function(err){
      if(err) console.log(err);
      console.log("moved");
    });
    
    0 讨论(0)
  • 2020-12-29 04:40

    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!

    0 讨论(0)
提交回复
热议问题