EHNole
EHNole

Reputation: 199

Parse JSON values from curl command in node.js

I'm able to get a stream of JSON from Twitter onto the client with this code:

var command = 'curl -d @tracking https://stream.twitter.com/1/statuses/filter.json -uUsername:Password'

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  child = exec(command);

  child.stdout.on('data', function(data) {

  res.write(data);

  });

}).listen(1337, "127.0.0.1");

but I can't get 'text' or 'id' value's from the JSON. I've tried using jQuery's parsJSON(), and other things such as code like this:

var command = 'curl -d @tracking https://stream.twitter.com/1/statuses/filter.json -uUsername:password'

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  child = exec(command);

  child.stdout.on('data', function(data) {

  for (i=0; i<data.length; i++) {
    reduceJSON = data[i]["text"]
    stringJSON = String(reduceJSON)
    res.write(stringJSON);
}

});

}).listen(1337, "127.0.0.1");

I keep getting streams of 'undefined' or 'readyStatesetRequestHeadergetAllResponseHeadersgetResponseHeader' or 'object:object'. Anyone know how to get individual values?

Upvotes: 2

Views: 5178

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161497

The short answer is that data is a string, not JSON. You need to buffer all of the data until child emits 'end'. After end has run, you need to use JSON.parse to convert the data into a JavaScript object.

That said, using a while separate cURL process makes no sense here. I would use the request module, and do something like this:

var request = require('request');
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});

  var r = request.post(
    'https://stream.twitter.com/1/statuses/filter.json',
    { auth: "Username:Password", 'body': "track=1,2,3,4" },
    function(err, response, body) {
      var values = JSON.parse(body);

      console.log(values);

    }
  );
  r.end();
}).listen(1337, "127.0.0.1");

Let me know if that doesn't quite work. I obviously don't have a user or password, so I can't test it.

Upvotes: 4

Related Questions