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 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.
  • flags: It is a number modifier for copy operation. Default value is 0. flags is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values.
    1. fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already exists.
    2. fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.
    3. fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.

Return Value: Promise. The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Create an original.txt file in the given directory to perform the following method. This example shows the copy operation of the original.txt file to copied.txtfile, if flag  is not given.



Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the 
// fsPromises.copyFile() method 
     
// Import the filesystem module 
const fs = require('fs'); 
const fsPromises = require('fs').promises;
  
fsPromises.copyFile("original.txt", "copied.txt")
.then(function() {
  console.log("File Copied");
})
.catch(function(error) {
  console.log(error);
});

chevron_right


Step to run this program:
Run index.js file using the following command:

node index.js

Output:

File Copied

Now you can see the copied.txt file is created in your current root directory.

Reference: https://nodejs.org/api/fs.html#fs_fspromises_copyfile_src_dest_mode

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.