0

everybody! I'm trying to build a Google Pagespeed client in nodejs. I get a json file with syntax errors for any url. For example: url: http://www.bbc.com/ , error: enter image description here json file:enter image description here

I need only the property "ruleGroups". I tried to extract it so jsonpath.query(d, '$.ruleGroups') - did not work out. Help please understand, sorry if the issue is dilettian.

    let key = 'key';
    let url = 'http://www.bbc.com/';
    let strategy = 'desktop';

    https.get({
    host: 'www.googleapis.com',
    path:  '/pagespeedonline/v4/runPagespeed?url=' + encodeURIComponent(url) +
    '&key='+key+'&strategy='+strategy
}, function (res) {
    console.log ("statusCode:", res.statusCode);
    console.log ("headers: ", res.headers);
    res.on ('data', function (d) {
        let json = JSON.parse(d);
        fs.appendFile('log.txt', json);
    });
}). on ('error', function (e) {
    console.error (e);
});

1 Answer 1

1

You may need to accumulate all the data, then parse in the “end” event:

let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
  try {
    const parsedData = JSON.parse(rawData);
    console.log(parsedData);
  } catch (e) {
    console.error(e.message);
  }
});

More information: https://nodejs.org/api/http.html#http_http_get_options_callback

Sign up to request clarification or add additional context in comments.

1 Comment

@Blackbonny That's awesome. If my answer was correct, please accept it. It helps you, me, and other readers when they find this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.