Node.js - copy files

0 points
Created by:

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) {

copyFileAsync('./sourceFile.txt', './destinationFile.txt');


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)

Alternative titles

  1. Node.js - how to copy files
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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.

❤️💻 🙂