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:
xxxxxxxxxx
1
const fs = require('fs');
2
3
fs.copyFile(pathToSourceFile, pathToDestinationFile, callback);
We use the fs.copyFile()
method from the file system (fs)
module. The contents of sourceFile.txt
will be copied to destinationFile.txt
.
xxxxxxxxxx
1
const fs = require('fs');
2
3
fs.copyFile('./sourceFile.txt', './destinationFile.txt', (error) => {
4
if (error) throw error;
5
console.log('copied successfully!');
6
});
xxxxxxxxxx
1
const { copyFile } = require('fs/promises');
2
3
const copyFileAsync = async (sourcePath, destinationPath) =>{
4
try {
5
await copyFile(sourcePath, destinationPath);
6
console.log('copied successfully!');
7
} catch (error) {
8
console.log(error);
9
}
10
}
11
12
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)