...

/

Solution: Check Your Directory

Solution: Check Your Directory

Exercise solution to "Check Your Directory" where the solution leverages asynchronous programming, promises, and async functions

We'll cover the following...

Solution

For the solution of the exercise, use the file reading function fs.readFile. Wrap it inside a promise to use it inside our async function. In our callback of the fs.readFile function, call resolve function if an error does or does not occurs, and supply it an array with the file name and boolean value. This makes each file name its own promise and uses the Promise.all function to resolve all of them together, along with the await token. See the solution below.

Press + to interact
index.js
misc.txt
temp.txt
random.js
content.txt
const fs = require('fs'); // import fs module
// promise creating function for any file read
function readFile(filename){ // function to return promise
return new Promise((resolve,reject) => {
fs.readFile(filename,'utf8', (err, data) => {
if(err){ // check for error
resolve([filename, false]); // file read unsuccessful
} else{
resolve([filename, true]); // file read successful
}
});
});
}
async function finder(filenames){
let promiseList = []; // list all promises
// populate promiseList with promises for each filename
filenames.forEach(x => {promiseList.push(readFile(x));});
data = await Promise.all(promiseList); // wait to resolve all promises
return data;
}
var ans = finder(['index.js', 'content.txt','funny.txt']);
ans.then(val => {console.log(val)});

In the code above, create a general function readFile (lines 3 to 13) which returns a promise for any file name (filename) provided as an argument. The promise returned on line 4 takes an anonymous function which calls resolve function from inside the fs.readFile function’s callback. We have two invocations for the resolve function for the following cases.

  • err value is not null(line 7): Indicates that the file reading was not successful, and so we provide an array as an argument to resolve function with filename and the value false.
  • err value is null(line 9): Indicates that the file reading was successful, and so we provide an array as an argument to resolve function with filename and the value true.

Given that, move onto creating the async function finder with the token async (line 15). First, initialize an empty array for promises and assign it to the promiseList variable (line 16). Then, iterate the filenames array. For each file name, fetch its corresponding promise via readFile function and push it to the array assigned to promiseList variable (line 18). Fetch an array with all returned values from all promises in promiseList array using the Promise.all function. Assign it to the data variable (line 19). Prepend await to it and wait for all promises to resolve before returning the data variable on line 20. The final answer shows the successful implementation.

This concludes the exercise!