How to Copy Files and Folders in Node.js – A JavaScript Guide

Whether you are a Mac, Linux or Windows user, we all copy and paste files from here to there regularly and if you think about this, it does not look like a very advanced feature but it is super crucial without which working with files becomes very difficult.

The same applies to programming languages, whether you are using Python, Java or our favourite Node.js, learning how to create functionality for copying files and folders is extremely important to make your application scalable and work with files seamlessly.

Well, if you are familiar with the Node.js built-in file system module, it’s just about a few lines of simple code.

In this tutorial, I will explain to you two ways, asynchronous and synchronous of copying files. Don’t worry if you are new to Node.js, I will bring some very basic code for this.

If you are someone who has no clue about the FS module, please read the attached tutorial, I recommend reading about it before learning how to copy, although it is not super mandatory.

Link: Node.js File System

Famous Ways to Copy Files in Node.js Using the FS Module

Did you know that Node.js is popular for writing asynchronous JavaScript code? This is what we are going to use. We will use its FS module’s super cool asynchronous and traditional synchronous methods to copy files and folder contents.

In an asynchronous method, the last argument is a completion callback. The arguments passed to the callback depend on the method. However, the first argument is always reserved for an error/exception so that if the operation fails, it can be used to find and resolve the error.

In the synchronous method, any errors are thrown immediately. To handle errors in a synchronous form, we can use try/catch blocks.

1. Copying Files Asynchronously Using copyFile() Method

FS copyFile() method is used to copy files from one directory to another directory in an asynchronous way. As a default behaviour, it overwrites the file if it already exists at the specified destination. 

Except for all the parameters, it also takes an optional argument mode which can be used to alter the behaviour of copying files.

Syntax:

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

Parameters:

  • 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 (by default it is 0),
  • callback (Function) – A callback function to check for an error.

Note:

To use this method in the script, we first need to import the fs module using the require module.

const fs = require('fs'); 

Example:

const fs = require('fs');

// 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"));
    }
});

Here we first imported the file system module, then used readFileSync() to print the content of the file, then used copyFile() to copy the content of the file to a new file, and inside the callback, we created a code to print the error message if the error is present and if an error does not occur then print the newly created file content.

sample_file.txt:

sample_file.txt

Output:

copyFile() Method

In the above output, you can see that the content of the newly created file is the same as the content of the previous file, so this method copied the file successfully.

In the above code, we have also used a method fs.readFileSync(), if you are interested to know how it actually works, follow this guide: How to Read a File in NodeJS

2. Copying Files Synchronously Using copyFileSync() Method

FS copyFileSync() method is used to copy files synchronously in Nodejs. The file will be created or overwritten by default if the file does not exist.

Similar to the fs.copyFile() method, this method also takes the optional argument mode to manipulate the behaviour of copying files but this one is the fastest way.

Syntax:

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

Parameters:

  • 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 (by default it is 0),

Example:

Let’s see an easy example of this method as well.

const fs = require('fs');

// 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"));

Here we first imported the file system module, then used readFileSync() to print the contents of the file, then used copyFileSync() to copy the contents of the file to a new file, and finally printed the newly created file to see if the content property is copied or not.

Output:

copyFileSync() Method

This way we have successfully copied a file from a source to a destination synchronously.

Conclusion

Just like we copy data, copying a file from one location to another in Node JS is an essential feature and we have seen both asynchronous (fs.copyFile) and synchronous (fs.copyFileSync) ways of doing this. We can access these functions by using the FS file object. Feel free to experiment with these methods and try to build a copy-paste functionality on your own web application to better understand the concept.

If you are new to Node.js:

References

Aneesha S
Aneesha S
Articles: 172