Friday, May 2, 2025

How to Copy a File in Node.js?

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.

How to Copy a File in Node.js?


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.

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!');
    }
});

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.

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


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

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


No comments:

Post a Comment