Async Copy in fs-extra - NodeJS

Node.jsServer Side ProgrammingProgramming

Introduction to Async copy

This method copies files or directories from one location to another location. The directory can have sub-directories and files.

Syntax

copy(src, dest[, options][, callback])

Parameters

  • src – This is a string paramter which will hold the source location of the file or directory that needs to be copies. If the location is a directory, it will copy everything inside of the directory instead of whole directory.

  • dest – This will hold the destination location where the files/directories will be copies. If src is a files, dest cannot be a directory.

  • options

    • overwrite – If set to true, existing files or directories will be overwritten. Default value is set to true.

    • errorOnExist – It will throw an error if the destination file/folder exists only when overwrite is set to false.

    • preserveTimestamps – Latest modification and access time will be set to that of the original files if true, else it will be OS dependent.

    • filter – This option will filter copied files. Will include filtered files if set to true.

  • callback – This function will give a callback if any error occurs.

Example

  • Check that fs-extra is installed before proceeding, if not, install fs-exra.

  • You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
  • Create a copyExample.js and copy-paste the following code snippet into that file.

  • Now, run the following command to run the code snippet.

node copyExample.js

Code Snippet

const fs = require('fs-extra')

// Copies file with a callback:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
   if (err) return console.error(err)
      console.log('success with callback!')
}) // Return a callback if any error occurs

// Copies directory from src to dest
fs.copy('/tmp/mydir', '/tmp/mynewdir', err => {
   if (err) return console.error(err)
      console.log('Directories copied successfully!')
})

// Copies file with Promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => {
   console.log('success with promise!')
})
.catch(err => {
   console.error(err)
})

// Copies file with async/await:
async function copyExample () {
   try {
      await fs.copy('/tmp/myfile', '/tmp/mynewfile')
      console.log('success with await!')
   } catch (err) {
      console.error(err)
   }
}
copyExample()

Output

C:\Users\tutorialsPoint\> node copyExample.js
success with callback!
success with promise!
success with await!
Directories copied successfully!
raja
Published on 27-Apr-2021 09:08:43
Advertisements