Languages
[Edit]
EN

Node.js - copy files

0 points
Created by:
Dirask JS Member
3670

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

Note: we use this method in this article too.

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 add fs.constants.COPYFILE_EXCL as the third argument of the method.

fs.copyFile(pathToSourceFile, pathToDestinationFile, fs.constants.COPYFILE_EXCL, callback)

Node.js - file system module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join