Solution to File Searcher

Solution overview to “File Searcher” using asynchronous programming

We'll cover the following...

Search

In this final step, use the previous function to get all text file paths and their data. Then, process them into a single object containing file paths as keys and an array of line numbers containing our query string as a value.

Press + to interact
var search = async (dir, token) => {
let data = await readFiles(dir);
let obj = {};
// filter out lines
data.forEach((val)=>{
let [directory, content]= val;
let lines = [];
content.split('\n').forEach((x, i)=>{
if(x.match(token)) lines.push(i); // add lines
})
if(lines.length !== 0) obj[directory] = lines;
});
return obj;
}
var test = async () => {
await populate_directory(); // initialise custom directories in background
var names = await search('dir', 'World'); // wait for async function
console.log(names); // print output of promise
}
test();

Begin by making the search function asynchronous by adding the async token to the function (line 1). ...