Solution to Sub-task: Read Files
The solution to the Sub-task "read files" of the project "File Searcher".
We'll cover the following...
Read files
Here, use the directories from earlier as a reference point. Read all files so the path and data of each file is in a single array.
Press + to interact
// helper function to read a file// input -> String => Path to file// Output -> [String, String] => [file path, data of file]var readFile = dir => new Promise(ress => fs.readFile(dir,'utf8',(err,data)=>{if(err) ress([dir ,'']);else ress([dir , data]);}))var readFiles = async (dir) => {var directories = await getNestedPathNames(dir);var txtFiles = directories.filter(x => x.match('.txt'));var txtpromises = txtFiles.map(x => readFile(x));var arrData = await Promise.all(txtpromises);return arrData}var test = async () => {await populate_directory(); // initialise custom directories in backgroundvar names = await readFiles('dir'); // get promise and wait for resolveconsole.log(names); // print output of promise}test();
In this solution, first make the readFiles
function asynchronous by adding the async
token to the function (line 9). Then, get all path names in the directory dir
utilizing our ...