How to Copy a File in Node.js?
Last Updated :
03 Jul, 2024
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:
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:
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:
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:
Similar Reads
How to copy folder recursively in Node.js ? Node.js is an enhancement to the already existing JavaScript. It is used for server-side scripting. It is mostly used to develop dynamic web applications. Node.js developers prefer the use of asynchronous functions over synchronous functions as the former does not block program execution under any c
3 min read
How to read and write files in Node JS ? NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to Access the File System in Node.js ? In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
3 min read
How to Download a File Using Node.js? Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries.Using
3 min read
How to Add Data in JSON File using Node.js ? JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article.Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
4 min read
How to handle file upload in Node.js ? File upload can easily be done by using Formidable. Formidable is a module that we can install on our project directory by typing the commandnpm install formidableApproach: We have to set up a server using the HTTPS module, make a form that is used to upload files, save the uploaded file into a temp
3 min read
How to Get Information About a File using Node.js ? Node.js is an open-source and cross-platform runtime environment built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isnât a framework, and itâs not a programming language. In this article, we will discuss how to get informatio
3 min read
Node.js fs.copyFileSync() Function The fs.copyFileSync() method is used to synchronously copy a file from the source path to destination path. Node.js will overwrite the file if it already exists in the destination. The optional mode parameter can be used to specify the behavior of the copy operation. Syntax:  fs.copyFileSync(src,
3 min read
How to work with Node.js and JSON file ? Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
4 min read
How to truncate a file using Node.js ? In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content. Method 1: The fs.truncate() method in Node.js ca
3 min read