Search⌘ K

Solution to File Searcher

Explore how to build an asynchronous file search function in JavaScript that retrieves text file paths and contents, then identifies line numbers containing specific search tokens. Understand key asynchronous techniques to handle file data and apply practical methods to return organized search results.

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.

Node.js
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). ...