The Wayback Machine - https://web.archive.org/web/20241004164614/https://www.geeksforgeeks.org/node-js-fs-copyfile-function/
Open In App

Node fs.copyFile() Function

Last Updated : 20 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The fs.copyFile() method is used to asynchronously copy a file from the source path to the destination path. By default, Node.js will overwrite the file if it already exists at the given destination. The optional mode parameter can be used to modify the behavior of the copy operation.

Syntax: 

fs.copyFile( src, dest, mode, callback )

Parameters: This method accepts three parameters as mentioned above and described below: 

  • src: It is a String, Buffer, or URL that denotes the source filename to copy.
  • dest: It is a String, Buffer, or URL that denotes the destination filename that the copy operation would create.
  • mode: It is an integer that specifies the behavior of the copy operation. The values can be given predefined constants that have their respective behaviours: 
    • fs.constants.COPYFILE_EXCL: This constant specifies that the copy operation would fail if the destination filename already exists.
    • fs.constants.COPYFILE_FICLONE: This constant specifies that the copy operation would try to create a copy-on-write reflink. A fallback mechanism is used if the platform does not support copy-on-write.
    • fs.constants.COPYFILE_FICLONE_FORCE: This constant specifies that the copy operation would try to create a copy-on-write reflink. The operation would fail if the platform does not support copy-on-write, unlike the previous one.

These constants can also be combined with bitwise OR to create a mask of more than one value. It is an optional parameter. The default value of the parameter is 0.

  • callback: It is a function that would be called when the method is executed. 
    • err: It is an error that would be thrown if the method fails.

Below examples illustrate the fs.copyFile() method in Node.js:

Example 1: This example shows the copy operation of the “example_file.txt” file to “copied_file.txt” file.

JavaScript
// Node.js program to demonstrate the
// fs.copyFile() method

// Import the filesystem module
const fs = require('fs');

// Get the current filenames
// before the function
getCurrentFilenames();
console.log("\nFile Contents of example_file:",
    fs.readFileSync("example_file.txt", "utf8"));

// Copying the file to a the same name
fs.copyFile("example_file.txt", "copied_file.txt", (err) => {
    if (err) {
        console.log("Error Found:", err);
    }
    else {

        // Get the current filenames
        // after the function
        getCurrentFilenames();
        console.log("\nFile Contents of copied_file:",
            fs.readFileSync("copied_file.txt", "utf8"));
    }
});

// Function to get current filenames
// in directory
function getCurrentFilenames() {
    console.log("\nCurrent filenames:");
    fs.readdirSync(__dirname).forEach(file => {
        console.log(file);
    });
}

Output: 

Current filenames:
example_file.txt
index.js
File Contents of example_file: This is a test file.
Current filenames:
copied_file.txt
example_file.txt
index.js
File Contents of copied_file: This is a test file.

Example 2: This example shows the failure of the copy operation when the destination already exists.

JavaScript
// Node.js program to demonstrate the
// fs.copyFile() method

// Import the filesystem module
const fs = require('fs');

// Get the current filenames
// before the function
getCurrentFilenames();
console.log("\nFile Contents of example_file:", 
      fs.readFileSync("example_file.txt", "utf8"));

// Copying the file to a the same name
fs.copyFile("example_file.txt", "copied_file.txt", 
      fs.constants.COPYFILE_EXCL, (err) => {
  if (err) {
    console.log("Error Found:", err);
  }
  else {

    // Get the current filenames
    // after the function
    getCurrentFilenames();
    console.log("\nFile Contents of copied_file:",
      fs.readFileSync("copied_file.txt", "utf8"));
  }
});

// Function to get current filenames
// in directory
function getCurrentFilenames() {
  console.log("\nCurrent filenames:");
  fs.readdirSync(__dirname).forEach(file => {
    console.log(file);
  });
}

Output: 

Current filenames:
copied_file.txt
example_file.txt
index.js
File Contents of example_file: This is a test file.
Error: [Error: EEXIST: file already exists, copyfile
'G:\tutorials\nodejs-fs-copyFile\example_file.txt' ->
'G:\tutorials\nodejs-fs-copyFile\copied_file.txt'] {
errno: -4075,
code: 'EEXIST',
syscall: 'copyfile',
path: 'G:\\tutorials\\nodejs-fs-copyFile\\example_file.txt',
dest: 'G:\\tutorials\\nodejs-fs-copyFile\\copied_file.txt'
}

Node fs.copyFile() Function – FAQs

How does the callback function work in fs.copyFile()?

The callback function receives an error object if the copy operation fails. If no error occurs, the copy is successful.

Can fs.copyFile() overwrite an existing file?

Yes, by default, fs.copyFile() overwrites the destination file. To prevent this, use the optional fs.constants.COPYFILE_EXCL flag.

Is fs.copyFile() synchronous or asynchronous?

fs.copyFile() is asynchronous by default. To use it synchronously, you can use fs.copyFileSync().

What is fs.constants.COPYFILE_EXCL in fs.copyFile()?

This flag prevents overwriting an existing file. If the destination file exists, fs.copyFile() will fail with an error.

Can I copy large files with fs.copyFile()?

Yes, fs.copyFile() handles large files efficiently, but it works asynchronously to avoid blocking the event loop.

We have a Cheat Sheet on Node fs modules where we covered all the fs methods to check those please go through Node File System Module Complete Reference this article. 



Previous Article
Next Article

Similar Reads

Node.js fsPromises.copyFile() Method
The fsPromises.copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, destination path is overwritten if it already exists. The Promise will be resolved with no arguments upon success. Syntax: fsPromises.copyFile( src, dest, flags ) Parameters: This method accepts three parameters as mentioned
2 min read
ASP CopyFile Method
The ASP CopyFile Method is used to copying one or more files from one place to another place. It is a predefined method of the FileSystem Object. Syntax: FileSystemObject.CopyFile source,destination[,overwrite] Parameter Values: Source: It is a required attribute. It contains a Character string file that can include wildcard characters, for one or
1 min read
What are the advantages of synchronous function over asynchronous function in Node.js ?
Node.js furnishes us with an inbuilt fs (File System) module for different documents taking care of tasks like reading a record, composing a document, erasing a document, and so on. fs module can be introduced utilizing the underneath explanation: Syntax: npm introduce fs --save Note: The npm in the above order represents the hub bundle supervisor
5 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
Encountering the error message ‘node’ is not recognized as an internal or external command after installing Node.js can be frustrating, especially when you’re eager to start working on your project. This error usually means that your system cannot find the Node.js executable because the path to it is not set correctly in your system's environment v
2 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
Node.js slice() function
The slice() function is a string function of Node.js which is used to extract sub-string from a string. Syntax: string.slice( start, end ) Parameters: This function uses three parameters as mentioned above and described below: string: It holds the string content. The substring is extracted from this string.start: This parameter holds the starting i
1 min read
Node.js crypto.scryptSync( ) Function
The crypto.scryptSync() is an inbuilt function which Provides a synchronous scrypt implementation in Node.js. scrypt is a password-based key derivation function. It is intended to be costly computationally plus memory-wise. So, the brute-force attacks are made unsuccessful. Syntax: crypto.scryptSync(password, salt, keylen[, options]) Parameter: Thi
3 min read
Node.js console.log() Function
The console.log() function from console class of Node.js is used to display the messages on the console. It prints to stdout with newline. Syntax: console.log( [data][, ...] ) Parameter: This function contains multiple parameters which are to be printed. Return type: The function returns the passed parameters. Below program demonstrates the working
1 min read
Node.js indexOf() function
The indexOf() function is a string function from Node.js which is used to find a string with another string. Syntax: str1.indexOf( str2 ) Parameter: This function uses two parameters as mentioned above and described below: str1: It holds the string content where another string is to be searched.str2: It holds the search string. Return Value: The fu
1 min read
Node.js trim() function
The trim() function is a string function of Node.js which is used to remove white spaces from the string. Syntax: string.trim() Parameter: This function does not accept any parameter. Return Value: The function returns the string without white spaces. The below programs demonstrate the working of trim() function: Program 1: C/C++ Code function trim
1 min read
Node.js substr() function
The substr() function is a string function of Node.js which is used to extract sub-string from the given string. Syntax: string.substr(index, length) Parameters: This function accepts two parameters as mentioned above and described below: index: This parameter holds the starting index of the specified sub-string.length: This parameter holds the len
1 min read
Node.js console.warn() Function
The console.warn() function from console class of Node.js is used to display the warning messages on the console. It prints to stderr with newline. Note: This function is an alias of console.error() function. Syntax: console.warn( [data][, ...args] ) Parameter: This function can contains multiple parameters. The first parameter is used for the prim
1 min read
Node.js console.error() Function
The console.error() function from the console class of Node.js is used to display an error message on the console. It prints to stderr with a newline. Syntax: console.error([data][, ...args]) Parameter: This function can contain multiple parameters. The first parameter is used for the primary message and other parameters are used for substitution v
1 min read
Node.js push() function
push() is an array function from Node.js that is used to add elements to the end of an array. Syntax: array_name.push(element) Parameter: This function takes a parameter that has to be added to the array. It can take multiple elements also. Return type: The function returns the array after adding the element. The program below demonstrates the work
1 min read
Node.js pop() function
pop() is an array function from Node.js that is used to remove elements from the end of an array. Syntax: array_name.pop() Parameter: This function does not take any parameter. Return type: The function returns the array. The program below demonstrates the working of the function: Example 1: C/C++ Code function POP() { arr.pop(); console.log(arr);
1 min read
Node.js shift() function
shift() is an array function from Node.js that is used to delete elements from the front of an array. Syntax: array_name.shift() Parameter: This function does not take any parameter. Return type: The function returns the array after deleting the element. The program below demonstrates the working of the function: Program 1: C/C++ Code function shif
1 min read
Node.js unshift() function
unshift() is an array function from Node.js that is used to insert elements to the front of an array. Syntax: array_name.unshift(element) Parameter: This function takes a parameter that has to be added to the array. It can take multiple elements also as parameters. Return type: The function returns the array after adding the element. The program be
1 min read
Node.js join() function
join() is an array function from Node.js that is used to return a string from the array. Syntax: array_name.join(parameter) Parameter: This function takes a single parameter as per which the join operation has to be performed. Return type: The function returns the string. The program below demonstrates the working of the function: Example 1: C/C++
1 min read
Node.js sort() function
sort() is an array function from Node.js that is used to sort a given array. Syntax: array_name.sort() Parameter: This function does not take any parameter. Return type: The function returns the sorted array. The program below demonstrates the working of the function: Program 1: C/C++ Code function sortDemo() { arr.sort() console.log(arr); } const
1 min read
Node.js GM drawLine() Function
The drawLine() function is an inbuilt function in the GraphicsMagick library which is used to draw the line with specified coordinates. The function returns the true value of success. Syntax: drawLine( x0, y0, x1, y1 ) Parameters: This function accepts four parameters as mentioned above and described below:. x0: This parameter stores the x-coordina
2 min read
Node.js GM drawArc() Function
The drawArc() function is an inbuilt function in the GraphicsMagick library which is used to draw an arc with specified coordinates. The function returns the true value of success. Syntax: drawArc( x0, y0, x1, y1, r0, r1 ) Parameters: This function accepts six parameters as mentioned above and described below:. x0: This parameter stores the value o
2 min read
Node.js GM drawPolyline() Function
The drawPolyline() function is an inbuilt function in the GraphicsMagick library which is used to draw polylines with specified coordinates. The function returns the true value of success. Syntax: drawPolyline( [x0, y0], ..., [xn, yn] ) Parameters: This function accepts the array of x and y coordinates. Return Value: This function returns the Graph
1 min read
Node.js GM drawBezier() Function
The drawBezier() function is an inbuilt function in the GraphicsMagick library which is used to draw the Bezier curve with specified coordinates. The function returns the true value of success. Syntax: drawBezier( [x0, y0], ..., [xn, yn] ) Parameters: This function accepts the array of points having x and y coordinates. Return Value: This function
1 min read
Node.js GM drawCircle() Function
The drawCircle() function is an inbuilt function in the GraphicsMagick library which is used to draw Circles with specified coordinates. The function returns the true value of success. Syntax: drawCircle( x0, y0, x1, y1 ) Parameters: This function accepts four parameters as mentioned above and described below:. x0: This parameter stores the x-coord
2 min read
Node.js GM drawEllipse() Function
The drawEllipse() function is an inbuilt function in the GraphicsMagick library which is used to draw an ellipse with specified coordinates. The function returns the true value of success. Syntax: drawEllipse( x0, y0, x1, y1, r0, r1 ) Parameters: This function accepts six parameters as mentioned above and described below: x0: This parameter stores
2 min read
Node.js GM drawPolygon() Function
The drawPolygon() function is an inbuilt function in the GraphicsMagick library which is used to draw a polygon with specified coordinates. The function returns the true value of success. Syntax: drawPolygon( [x0, y0], ... ,[xn, yn] ) Parameters: This function accepts the array of x and y coordinates. Return Value: This function returns the Graphic
1 min read