EN
Node.js - copy files
0
points
In this article, we would like to show you how to copy files in Node.js.
Quick solution:
const fs = require('fs');
fs.copyFile(pathToSourceFile, pathToDestinationFile, callback);
Practical example
We use the fs.copyFile()
method from the file system (fs)
module. The contents of sourceFile.txt
will be copied to destinationFile.txt
.
const fs = require('fs');
fs.copyFile('./sourceFile.txt', './destinationFile.txt', (error) => {
if (error) throw error;
console.log('copied successfully!');
});
Async/await example
const { copyFile } = require('fs/promises');
const copyFileAsync = async (sourcePath, destinationPath) =>{
try {
await copyFile(sourcePath, destinationPath);
console.log('copied successfully!');
} catch (error) {
console.log(error);
}
}
copyFileAsync('./sourceFile.txt', './destinationFile.txt');
Note:
In the examples above, the target file will be overwritten or created if it does not exist.
If we want the copy to fail when there is a file, we need to addfs.constants.COPYFILE_EXCL
as the third argument of the method.
fs.copyFile(pathToSourceFile, pathToDestinationFile, fs.constants.COPYFILE_EXCL, callback)