-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
improving async filesystem callbacks
- Loading branch information
1 parent
9ab74f4
commit 5c700d1
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |