0

[EDIT]

I figured it out. The code ends up like this:

//getTrelloJSON.js
var request = require('request');
'use strict';

function getProjJSON(requestURL, callback){
    request.get({
        url: requestURL,
        json: true,
        headers: {'User-Agent': 'request'}
      }, (err, res, data) => {
        if (err) {
            console.log('Error:', err);
        } else if (res.statusCode !== 200) {
            console.log('Status:', res.statusCode);
        } else {
            callback(data);
        }
    });
}

module.exports.getProjJSON = getProjJSON;

And

//showData.js
var getJSON = require('./getTrelloJSON');

getJSON.getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json', (result) => {
    var lists = result.lists;
    console.log(lists);
});

I run node showData.js and it gets the json and then I can manipulate it as needed. I printed just to show it works.

[EDIT END]

I'm new to node.js and I am facing a noob problem. This code is supposed to request a JSON from a public trello board and return an object with a section of trello's json (lists section).

The first console.log() does not work but the second does.

How do I make it wait for the completion of getProjJSON() before printing it?

var request = require('request');
'use strict';

//it fails
console.log(getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json'));

function getProjJSON(requestURL){
    request.get({
        url: requestURL,
        json: true,
        headers: {'User-Agent': 'request'}
      }, (err, res, data) => {
        if (err) {
          console.log('Error:', err);
        } else if (res.statusCode !== 200) {
          console.log('Status:', res.statusCode);
        } else {
          //it works
          console.log(data.lists);
          return data.lists;
        }
    });
}
  • Node.js is all about callbacks. If you want to console.log (data.lists), just log inside the response body. – forqzy Dec 21 '17 at 04:36
  • The first console.log is just to show the JSON obj is not ready when it tries to print. The code needs to wait for the json to be loaded before returning it. I just don't know how to do it. – Caio Marchi Dec 21 '17 at 04:53

1 Answers1

0

Node.js is all about callbacks. And here you just not register the callbacks for data.

var client       = require('http');
var options = {
            hostname: 'host.tld',
            path: '/{uri}',
            method: 'GET', //POST,PUT,DELETE etc
            port: 80,
            headers: {} //
          };
    //handle request;
pRequest    = client.request(options, function(response){
console.log("Code: "+response.statusCode+ "\n Headers: "+response.headers);
response.on('data', function (chunk) {
      console.log(chunk);
});
response.on('end',function(){
      console.log("\nResponse ended\n");
});
response.on('error', function(err){
      console.log("Error Occurred: "+err.message);
});

});

or here is a full example, hope this solve your problem

const postData = querystring.stringify({
  'msg' : 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`res_code: ${res.statusCode}`);
  console.log(`res_header: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`res_data: ${chunk}`);
  });
  res.on('end', () => {
    console.log('end of response');
  });
});

req.on('error', (e) => {
  console.error(`response error ${e.message}`);
});

//write back 
req.write(postData);
req.end();
forqzy
  • 389
  • 2
  • 11