1

I just started learning Node.js.

I am trying to return the body of the response by using node-fetch but I received an undefined output. I should get a '0' as response but I am getting '200 undefined'

this is from the target website where I am trying to get '0'

<td id="pendingBlocks" style="text-align:center;vertical-align: middle;">0</td>

this is the script.

const fetch = require("node-fetch");
async function getCourseCode() {
    try {
        let response = await fetch('https://websitehere');
        let body = await response.text();
        console.log(response.status);
        //console.log(body);
        let responseBody = body.match("pendingBlocks");
        let pending = responseBody[1];
        console.log(pending);
    }
    catch(exception){
        console.log(exception);
    }
}

getCourseCode();
Onur Keles
  • 11
  • 1
  • `body.match("pendingBlocks")` executes the regular expression `"pendingBlocks"` on the text of the body. And returns the result of that match as an array (in your case it will be `["pendingBlocks"]` because you don't have any capture groups). You will need some html parser for that ... – derpirscher Aug 13 '21 at 15:55
  • To get data from HTML, the most reliable way is to use healdess browsers, like https://github.com/puppeteer/puppeteer/ – vsemozhebuty Aug 14 '21 at 15:30

1 Answers1

0

I used cheerio to get my id's output. I just want to share so if someone else is looking for the same node.js.

const cheerio = require('cheerio');
const request = require('request');

request({
    method: 'GET',
    url: 'Website URL here'
}, (err, res, body) => {
    if (err) return console.error(err);
    $ = cheerio.load(body);
    var element = $('#pendingBlocks');
    var element2 = $('#confirmedBlocks');
    if (Number(element.text())+Number(element2.text()) === 0) {
    console.log('true')
}else{
  console.log('false')
}
});
Onur Keles
  • 11
  • 1