Skip to content

Commit

Permalink
improving async filesystem callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
dasanupam1001 committed Aug 21, 2023
1 parent 9ab74f4 commit 5c700d1
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
48 changes: 48 additions & 0 deletions 15-improved-async-filesystem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* improved asynchronous filesystem (instead of using nested callbacks) */


const { readFile, writeFile } = require('fs').promises // instead of importing util and then doing util.promisify, we can derectly call require('fs').promises

// const util = require('util')
// const readFilePromise = util.promisify(readFile)
// const writeFilePromise = util.promisify(writeFile)



const start = async() => {
// always place async await functions in try catch block
try {
// const first = await readFilePromise('./content/first.txt', 'utf-8')
const first = await readFile('./content/first.txt', 'utf-8')
// const second = await readFilePromise('./content/second.txt', 'utf-8')
const second = await readFile('./content/second.txt', 'utf-8')
// await writeFilePromise('./content/result-improved-async.txt', `Here is the improved async file:\n${first}\n${second}`)
await writeFile('./content/result-improved-async.txt', `Here is the improved async file:\n${first}\n${second}`)

console.log(first + '\n' + second)
} catch (error) {
console.log(error)
}
}

start()

/*
// slight improvement on async readFile : instead of using nested for loops we are using a bit cleaner approach
// Promise makes the particular program wait until all the programs run
const getText = (path) => {
return new Promise((resolve, reject) => {
readFile(path,'utf8', (err, data) => {
if(err){
reject(err)
return
} else {
resolve(data)
}
})
})
}
getText('./content/first.txt')
.then(result => console.log(result))
.catch(err => console.log(err))
*/
3 changes: 3 additions & 0 deletions content/result-improved-async.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Here is the improved async file:
hello this is the first text
hello this is the second text

0 comments on commit 5c700d1

Please sign in to comment.