Open In App

Node.js fsPromises.copyFile() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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




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


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


Last Updated : 08 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads