Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SyntaxError: Unexpected token in node.js

SyntaxError: Unexpected token in node.js

Problem

Am using following code to fetch data from server .but in place of

var  jobData = JSON.parse(data);

Am getting

undefined:1
1afcec877d925d110","date":"Mon Jan 06 2014 09:33:13 GMT+0530 (IST)","id":"51",
                                                                              ^
SyntaxError: Unexpected end of input
    at Object.parse (native)

code

var options = {
                    host: '172.16.2.120',
                    path: '/getModes?mode=' + jobLists,
                    port: '8080',
                    method: 'GET'
                };

                var reqOs = http.request(options, function (resOs) {
                    resOs.on('data', function (data) {              
                   var jobData = JSON.parse(data);              
                    });
                    resOs.on('end', function () {           

                    });
                });
                reqOs.on('error', function (e) {
                    console.log('problem with request: ' + e.message);
                });
                reqOs.end(''); 
Problem courtesy of: Sush

Solution

You need to accumulate the chunks of data passed to the data event handler, and process them when the HTTP request has ended:

var reqOs = http.request(options, function (resOs) {
  var chunks = [];
  resOs.on('data', function (chunk) {
    chunks.push(chunk);
  });
  resOs.on('end', function () {
    var json    = Buffer.concat(chunks);
    var jobData = JSON.parse(json);
    ...
  });
});

The reason for this is that the data event can be triggered in the middle of reading a response.

Solution courtesy of: robertklep

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

SyntaxError: Unexpected token in node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×