My intent is to write a function that takes an html file converted to a string and returns an array populated with all of the links from the html file.
The following code returns an empty array:
const fs = require("fs");
function findURLs(filePath) {
let URLArray = [];
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) throw err
let index = 0
while (index !== -1) {
let positionOfUrlMarker = data.indexOf("a href=", index);
if (positionOfUrlMarker === -1) {
index = -1;
} else {
let firstIndexOfUrl = data.indexOf("\"", positionOfUrlMarker);
let lastIndexOfUrl = data.indexOf("\"", firstIndexOfUrl + 1);
let foundUrl = data.slice(firstIndexOfUrl + 1, lastIndexOfUrl);
let URLObject = { "URL": foundUrl };
URLArray.push(URLObject);
index = lastIndexOfUrl;
}
}
})
return URLArray
}
I have also tried replacing "index = -1" with the return statement. When I do this, the function returns undefined.
I tend to run into problems like this when I code and I assume it's because there's some important rule that I don't understand. Can anybody identify what I'm doing wrong?