Sunday 27 September 2020

[HELP] Use promises to read file and then asynchronously send head requests

Hi, I am learning node and I am really frustrated at this point with promises and just asynchronous programming. I have no idea what I am doing. I am going back and forth on multiple things and I'm just lost. I would appreciate it if someone can point me in the right direction.I want to read a file full of URLs (using fs.readFile promise version - not callback). I want use a regex to match all URLs and then store them as a string to a variable called URL list (or maybe even make it an array and push to it. whatever is more efficient). Then I want to asynchronously send requests to all those URLs in urlList which must happen after the readFile is done? I get an error in await read file line saying.await is only valid in async functionI would really appreciate your help!My code so far:let urlList; try { const data = await fs.readFile(argv.file);const dataString = data.toString(); urlList = dataString.match(/(http|https)(://)([\w+-&@`~#$%*.=/?:]+)/gi); console.log(urlList);   } catch (err) { console.err(err);   }urlList.forEach(async (url) => { try { const urlTest = await fetch(url, { method: "head" }); if (urlTest.status == 200) { console.log( chalk.green.bold(`[GOOD] Status: [${urlTest.status}] ${url}`) ); } else if (urlTest.status == 400 || urlTest.status == 404) { console.log(chalk.red.bold(`[BAD] Status: [${urlTest.status}] ${url}`)); } else { console.log( chalk.grey.bold(`[UNKNOWN] Status: [${urlTest.status}] ${url}`) ); } } catch (error) { console.log(chalk.grey.bold(`[UNKNOWN] Status: [UNKNOWN] ${url}`)); } });

Submitted September 27, 2020 at 02:39PM by fothingers

No comments:

Post a Comment