Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to both synchronous and asynchronous operations.
Methods to Copy Files in Node.js
Node.js provides multiple approaches to copy files, including the traditional fs.copyFile method, stream-based copying, and utilizing third-party libraries. Each method has its own use cases, advantages, and trade-offs.
Table of Content
Steps to Setup Project
Step 1: Make a folder structure for the project.
mkdir myappStep 2: Navigate to the project directory
cd myappStep 3: Initialize the NodeJs project inside the myapp folder.
npm init -yProject Structure:

Using fs.copyFile (Asynchronous)
The fs.copyFile method is a straightforward way to copy files asynchronously. It is non-blocking, which means your application can continue to handle other tasks while the file is being copied.
Example: Implementation to show copying a file in NodeJS.
// app.js
const fs = require('fs');
const source = 'source.txt';
const destination = 'destination.txt';
fs.copyFile(source, destination, (err) => {
if (err) {
console.error('Error copying file:', err);
} else {
console.log('File copied successfully!');
}
});
Output:

Using fs.copyFileSync (Synchronous)
The fs.copyFileSync method is the synchronous version of fs.copyFile. It blocks the execution of code until the file copying operation is complete.
Example: Implementation to show copying a file in NodeJS.
// main.js
const fs = require('fs');
const source = 'source.txt';
const destination = 'destination.txt';
try {
fs.copyFileSync(source, destination);
console.log('File copied successfully!');
} catch (err) {
console.error('Error copying file:', err);
}
Output:

Using fs-extra Library
The fs-extra library extends Node.js's fs module with additional functionality, including a simpler and more robust copy method.
Installation:
npm install fs-extraThe updated dependencies in package.json file will look like:
"dependencies": {
"fs-extra": "^11.2.0",
}
Example: Implementation to show copying a file in NodeJS.
// main.js
const fs = require('fs-extra');
const source = 'source.txt';
const destination = 'destination.txt';
fs.copy(source, destination)
.then(() => {
console.log('File copied successfully!');
})
.catch((err) => {
console.error('Error copying file:', err);
});
Output:
