Open In App

How to Copy a File in Node.js?

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Steps to Setup Project

Step 1: Make a folder structure for the project.

mkdir myapp

Step 2: Navigate to the project directory

cd myapp

Step 3: Initialize the NodeJs project inside the myapp folder.

npm init -y

Project Structure:

Screenshot-2024-07-02-092449

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.

Node
// 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:

Screenshot-2024-07-02-092324

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.

Node
// 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:

Screenshot-2024-07-02-092324

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-extra

The updated dependencies in package.json file will look like:

"dependencies": {
"fs-extra": "^11.2.0",
}

Example: Implementation to show copying a file in NodeJS.

Node
// 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:

Screenshot-2024-07-02-092324




Next Article

Similar Reads