From 854e70a210c061cd5046372081714830140a62f9 Mon Sep 17 00:00:00 2001 From: Tapajyoti Bose <44058757+ruppysuppy@users.noreply.github.com> Date: Sat, 1 Aug 2020 09:14:10 +0530 Subject: [PATCH] Added stock price fetch + package-lock.json (#233) * Added stock price fetch * Delete package-lock.json Co-authored-by: vinayak --- Web-Programming/StockPrice.js | 30 ++++++++++++++++++++++++++++++ package.json | 1 + 2 files changed, 31 insertions(+) create mode 100644 Web-Programming/StockPrice.js diff --git a/Web-Programming/StockPrice.js b/Web-Programming/StockPrice.js new file mode 100644 index 000000000..f2e656305 --- /dev/null +++ b/Web-Programming/StockPrice.js @@ -0,0 +1,30 @@ +const fetch = require('node-fetch') +const jsdom = require('jsdom') + +// function to get the stock price from the given symbol +async function getStockPrice (stockSymbol) { + // parsing the html page body + const url = `https://in.finance.yahoo.com/lookup?s=$${stockSymbol}` + const response = await fetch(url) + const pageBody = await response.text() + const dom = new jsdom.JSDOM(pageBody, 'text/html') + // returning the price as a number + return parseFloat(dom.window.document.querySelectorAll('td')[2].textContent.replace(/,/g, '')) +} + +async function main () { + // Using async await to ensure synchronous behaviour + await getStockPrice('GOOGL') + .then(response => console.log(`GOOGL stock price: $ ${response}`)) + + await getStockPrice('AAPL') + .then(response => console.log(`AAPL stock price: $ ${response}`)) + + await getStockPrice('MSFT') + .then(response => console.log(`MSFT stock price: $ ${response}`)) + + await getStockPrice('AMZN') + .then(response => console.log(`AMZN stock price: $ ${response}`)) +} + +main() diff --git a/package.json b/package.json index f827648c3..ac36071f0 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "author": "TheAlgorithms", "license": "GPL-3.0", "dependencies": { + "jsdom": "^16.3.0", "node-fetch": "2.6.0" }, "devDependencies": {