How to Copy Files with Nodejs – 2021 Guide

As I promised you all, I have come back with yet another method from the file system module i.e. how to copy files with Nodejs. And as I always say, the fs or file system module is really vast and one of the most important built-in modules in Node.js.

In this tutorial, I am going to cover up how to copy files with Node.js. Well, there are many use cases to this function. You might come across situations where you want to copy data from a file and maybe put it into use later in your code.

However, copying a file in Node.js is not the same as reading a file and then writing its contents in another file.

All fs module functions or methods have their asynchronous and synchronous forms, which we will cover in this article.

In an asynchronous form, the last argument is always a completion callback. The arguments passed to the callback depend on the method. However, the first argument is always reserved for an error/exception.

If in case, the operation fails to complete, the first argument will be undefined otherwise, it will be null.

In the synchronous version of a method, any error is thrown immediately. To handle errors in synchronous forms, we can always make use of try/catch or simply allow them to bubble up.

Copying Files Asynchronously in Node.js

fs.copyFile(src, dest[, mode], callback)

The fs.copyFile() method helps us to copy files with Nodejs asynchronously from a source to a destination. As a default behavior, Node.js overwrites the file if it already exists, at the specified destination.

The mode parameter/argument that this method accepts, is optional. However, it can be used to alter the behavior of copying file(s).

Below are the parameters listed that the fs.copyFile accepts:

  • src – String, buffer or URL. Represents source file name to copy
  • dest – String, Buffer or URL. Represents destination file name to create
  • mode – Optional Integer. Represents modifiers of the copy operation. Default = 0. Read about the predefined constants here.
  • callback – The function to be executed, when the method is called.
  • err – The error to be thrown in case of exceptions.

To learn to copy files with Nodejs, we must first import our fs module using the require module.

const fs = require('fs');

Let us cite an example so we can understand the function better:

// Printing the current file name before copying
console.log("File Contents of sample_file:",
  fs.readFileSync("sample_file.txt", "utf8"));
 
// Copying sample_file.txt to a different name
fs.copyFile("sample_file.txt", "async_copied_file.txt", (err) => {
  if (err) {
    console.log("Oops! An Error Occured:", err);
  }
  else {
    // Printing the current file name after executing the function
    console.log("File Contents of async_copied_file:",
      fs.readFileSync("async_copied_file.txt", "utf8"));
  }
});

Output:

File Contents of sample_file: This is a sample file for the async copy operation.
File Contents of async_copied_file: This is a sample file for the async copy operation.

This way, you can asynchronously copy files from any source to any destination. Don’t understand what fs.readFileSync() does? Check out my post on reading files in Node.js.

Copying Files Synchronously in Node.js

fs.copyFileSync(src, dest[, mode])

The fs.copyFileSync() method helps us to copy files with Nodejs synchronously from a source to a destination. As a default behavior, Node.js overwrites the file if it already exists, at the specified destination.

The mode parameter/argument that this method accepts, is optional. However, it can be used to alter the behavior of copying file(s).

Below are the parameters listed that the fs.copyFileSync accepts:

  • src – String, buffer or URL. Represents source file name to copy
  • dest – String, Buffer or URL. Represents destination file name to create
  • mode – Optional Integer. Represents modifiers of the copy operation. Default = 0. Read about the predefined constants here.

To copy files with Nodejs, we must first import our fs module using the require module.

const fs = require('fs');

Let us illustrate this method or function with a similar example:

// Printing the current file name before copying
console.log("File Contents of sample_file:",
  fs.readFileSync("sample_file.txt", "utf8"));
 
// Copying sample_file.txt to a different name
fs.copyFileSync("sample_file.txt", "sync_copied_file.txt);

  // Printing the current file name after executing the function
    console.log("File Contents of sync_copied_file:",
      fs.readFileSync("sync_copied_file.txt", "utf8"));

Output:

File Contents of sample_file: This is a sample file for the sync copy operation.
File Contents of sync_copied_file: This is a sample file for the sync copy operation.

This way, you can synchronously copy files from any source to any destination.

Conclusion

The fs or file system module is really vast and one of the most important built-in modules in Node.js. In this tutorial, I have covered, copying files with Node.js. you can expect more posts on the different methods on the fs module!

Noteworthy References

Copy File (Synchronous) – Node.js Official Docs

Copy File (Asynchronous) – Node.js Official Docs

Aneesha S
Aneesha S
Articles: 175