Sync vs Async vs Async/Await in fs-extra - NodeJS


Introduction to fs-extra

Before proceeding with fs-extra, one must have a basic knowledge of the fs file system. The fs-extra is an extension of the fs file system and has more methods than it. It adds some file method systems that are not there in the naive fs modules. Fs-extra adds the promise support to the fs methods and therefore better than fs.

Installation

npm install fs-extra

Syntax

fs-extra is a replacement for the native fs file system. All methods that are in fs are attached to fs-extra as well. Therefore, you don't need to include fs again.

const fs = require('fs-extra');

Most methods provided by fs-extra are async, by default. Async methods return a promise if any callback isn't configured.

Example

  • Check that fs-extra is installed before proceeding

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

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

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

node copyFiles.js

Code Snippet

// fs-extra imported for use
const fs = require('fs-extra')

// Copying file using Async with promises:
fs.copy('/tmp/myfile, '/tmp/myAsyncNewfileWithPromise')
   .then(() => console.log('Async Promise Success!'))
   .catch(err => console.error(err))

// Copying file using Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/myAsyncNewfileWithCallback', err => {
   if (err) return console.error(err)
   console.log('Async Callback Success!')
})

// Copying file using Sync:
try {
   fs.copySync('/tmp/myfile', '/tmp/mySyncNewfile')
   console.log('Sync Success!')
} catch (err) {
   console.error(err)
}

// Copying file using Async/Await:
async function copyFiles () {
   try {
      await fs.copy('/tmp/myfile', '/tmp/myAwaitFile')
      console.log('Await Success!')
   } catch (err) {
      console.error(err)
   }
}

copyFiles()
console.log("All files copied succesfully !!!")

Output

C:\Users\tutorialsPoint\> node copyFiles.js
Sync Success!
All files copied succesfully !!!
Async Promise Success!
Await Success!
Async Callback Success!

Updated on: 28-Apr-2021

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements