I'm writing a simple Node.JS app that works with the GitHub API to pull user statistics. I'm sending a GET request to /repos/:user/:repo_name/stats/contributors
which should return to me a JSON string. Here's my function:
function getRepoCommits(token,repos,user,callback) {
for (var i=0; i<repos.length; i++) {
var returnChunk = '';
var full_name = repos[i].full_name;
//console.log(full_name);
var options = {
host: 'api.github.com',
path: '/repos/'+full_name+'/stats/contributors',
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': 'token '+token,
'Content-Type': 'application/x-www-form-urlencoded',
}
};
var request = https.request(options, function(res) {
//res.setEncoding('utf8');
res.on('data', function(chunk) {
returnChunk += chunk;
});
res.on('end', function(chunk) {
console.log(returnChunk);
var stats = JSON.parse(returnChunk);
console.log(stats.length);
for (var j=0;j<stats.length;j++) {
}
if (i == repos.length-1) {
//callback();
}
})
});
request.on('error',function(err) {
callback(err);
console.log(err);
});
request.end();
}
}
The area of interest is right here:
res.on('end', function(chunk) {
console.log(returnChunk);
var stats = JSON.parse(returnChunk);
console.log(stats.length);
for (var j=0;j<stats.length;j++) {
}
if (i == repos.length-1) {
//callback();
}
})
When I check the value of returnChunk
, it is a valid JSON string in the format :
[{json}]
However, when the function reaches JSON.parse
, it throws an error:
SyntaxError: Unexpected token [
Basically, it's appending an extra []
to the end of the string before parsing it. It becomes
[{json}][]
I've tried for hours on end to figure out how to deal with this problem, but I can't seem to figure out why it is doing this. Any thoughts?
[]
to the end? Where do you see that in your logging? – Blue Skies 21 hours agoreturnChunk
variable, so all your data is getting mixed together. Remember, JavaScript doesn't have block scope, only function scope, so it's as if you putvar returnChunk = ""
at the top of the function. – Blue Skies 21 hours ago