How to copy a file using Node.js

To copy a file in Nodejs:

  1. Use the fs.copyFile() method from the native file system module.
  2. Pass the source filename, the destination filename, an optional modifier for the copy operation, and a callback function as parameters.
  3. The callback function gets called with an error object or null depending on the status of the copy operation.

Here is an example:

const fs = require('fs')

fs.copyFile('src.txt', 'dest.txt', err => {
  if (err) {
    console.error(err)
  }

  console.log(`src.txt was copied to dest.txt!`)
})

The fs.copyFile() method copies source file to destination file. By default, if the destination file already exists, it is overwritten.

However, you can pass an optional integer as a third parameter that specifies the behavior of the copy operation:

  • fs.constants.COPYFILE_EXCL — The copy operation will fail if destination file already exists.
  • fs.constants.COPYFILE_FICLONE — The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.
  • fs.constants.COPYFILE_FICLONE_FORCE — The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
// Fail if dest.txt already exists
fs.copyFile('src.txt', 'dest.txt', fs.constants.COPYFILE_EXCL, err => {
  if (err) {
    console.error(err)
  }

  console.log(`src.txt was copied to dest.txt!`)
})

To synchronously copy the source file to the destination file, use the fs.copyFileSync() method instead:

const fs = require('fs')

fs.copyFile('src.txt', 'dest.txt')
console.log(`src.txt was copied to dest.txt!`)

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.