To copy a file in Nodejs:
- Use the
fs.copyFile()
method from the native file system module. - Pass the source filename, the destination filename, an optional modifier for the copy operation, and a callback function as parameters.
- 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.