Copying files in Node.js can prove to be a difficult task if you are not familiar with its built-in File System module. However, you will find it easy and efficient once you get the hang of it.
Copying files comes in handy when you may come across situations where you want to copy data from one directory to another directory.
In this tutorial, we will explore both asynchronous and synchronous ways of copying files. Whether a beginner or an experienced Node.js developer, this guide will help you learn new things about Node.js file manipulation.
Multiple ways to Copy Files in Node.js using the FS module
FS module methods have both asynchronous and synchronous ways to copy file and folders content.
In the asynchronous form, 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 to meet it, the first argument can be used to find and resolve the error.
In the synchronous version of a method, any errors are thrown immediately. To handle errors in synchronous forms, we can use try/catch blocks.
Copying Files Asynchronously using copyFile() method
The copyFile() method helps us to copy files asynchronously from one directory to another directory in Node js. As a default behaviour, it overwrites the file if it already exists at the specified destination.
This method can take an optional argument mode. It can be used to alter the behaviour of copying file(s).
Syntax:
Below is the syntax for using the fs.copyFile() method.
fs.copyFile(src, dest[, mode], callback)
where:
- 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 – A callback function to check for an error
To use this method in Node.js, we must first import the fs module using the require module.
const fs = require('fs');
Let us cite an example so we can understand the function better.
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 have written 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.
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.
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.
This way, you can asynchronously copy files from any source to any destination. Don’t understand what fs.readFileSync() does? Check out our tutorial on reading files in Node.js.
Copying Files Synchronously using copyFileSync() method
The copyFileSync() method helps us to copy files synchronously in Nodejs from one directory to another directory. As a default behaviour, Node.js overwrites the file if it already exists at the specified destination.
Similar to the fs.copyFile() method, this method also takes an optional argument mode which can be used to alter the behaviour of copying file(s). It is the fastest way to copy a file.
Syntax:
Below is the syntax for using the fs.copyFileSync() method.
fs.copyFileSync(src, dest[, mode])
where:
- 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)
Let us illustrate this method with a similar example.
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.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:
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
In this tutorial, we have learned that we can copy files in Node.js using the File system module which has two methods, fs.copyFile() to copy files asynchronously and fs.copyFileSync() to copy files synchronously. You can choose one as per your requirement. Hope you find this tutorial helpful.
References
https://nodejs.org/api/fs.html#fscopyfilesrc-dest-mode-callback
https://nodejs.org/api/fs.html#fscopyfilesyncsrc-dest-mode