Open In App

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:

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

Article Tags :