fetching data from json not showing on browser

Viewed 21

this functionality is new to me, im building this with the help of a tutorial but since the tutorial fetched a different set of data i got lost.

const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://br.tradingview.com/symbols/TVC-DXY/',{
    waitUntill: 'load',
    timeout: 0
  });
  
  /*const element = await page.$(".tv-symbol-header__first-line");
  const text = await page.evaluate(element => element.textContent, element);*/

  const textNode = await page.evaluate(()=>{
    const nodeText = document.querySelector(".tv-symbol-price-quote__change-value").innerText;
    const text = [nodeText];
    
    return text
  });

  fs.writeFile('arreglo.json', JSON.stringify(textNode), err =>{
    if (err) throw new Error ('algo deu errado')
      console.log('deu certo')
  })
  //await browser.close();
})();
<script>
    (async() => {
    const response = await fetch('./arreglo.json')
    const data = await response.json();

    document.querySelector(".container").innerHTML = data
    })();
</script>

the first part is index.js

the second piece of code is in the html script.

the file arreglo.json is created and the result is like this: ["+0.887"]

i just want the 0.887, but i could format, not a problem, but i cant seem to get it on the html page.

1 Answers

It would be helpful to see the rest of your HTML code, or at least where you have placed the script tag as you have used a querySelector as part of the fetch request to render the data. Javascript code runs in order so if your script tag is before the ".container" element then your script will run before the ".container" element is available to render the data.

If you haven't already then I would place your script tags at the bottom of your HTML page so that all static content is rendered before any scripts start to amend it:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="container">
        Content here...
    </div>
    <script>
      (async() => {
      const response = await fetch('./arreglo.json')
      const data = await response.json();

      document.querySelector(".container").innerHTML = data
      })();
    </script>
</body>
</html>
Related