
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sync vs Async vs Async/Await in FS Extra Node.js
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!