# How to copy a file using Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 9, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-copy-file

> Learn how to use the copyFile() method from the native fs module to copy a file in 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:

```javascript
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` &mdash; The copy operation will fail if destination file already exists.
* `fs.constants.COPYFILE_FICLONE` &mdash; 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` &mdash; 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.

```javascript
// 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:

```javascript
const fs = require('fs')

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