node.js - Error parsing array containing buffers from two sequential Youtube API requests -
i trying playlists on youtube channel. chunks
parses no problem when request either 1st https.get (first 50 playlist titles) or 2nd(nested) https.get(next 50 playlist titles)
however, if both requests , push 100 titles (5 buffers each request) chunks
, parsing problem unexpected token { in json @ position 6508.
how can parse chunks
contains information of 100 titles both https.get instead of either first 50 or next 50 only?
full parsable (first 50 playlist) code below:
var util = require('util'); var https = require('https'); var fs = require('fs'); var count = 1; https.get('https://www.googleapis.com/youtube/v3/playlists?maxresults=50&fields=items(snippet/title,contentdetails)&part=snippet%2ccontentdetails&channelid=ucjbpgzawdh1njbqv-d5hqkw&key=aizasydgkgcw_vv8onuonht-dgeww3uryomsfzu',function(response){ console.log("status code is: "+response.statuscode); var chunks = []; //var chunks = new buffer(0); response.on('data', (json) => {chunks.push(json);}); // response.on('data', (json) => {chunks = buffer.concat([chunks ,json]); }) //if using chunks = new buffer(0) response.on('end',() => { https.get('https://www.googleapis.com/youtube/v3/playlists?pagetoken=cdiqaa&maxresults=50&fields=items(snippet/title,contentdetails)&part=snippet%2ccontentdetails&channelid=ucjbpgzawdh1njbqv-d5hqkw&key=aizasydgkgcw_vv8onuonht-dgeww3uryomsfzu',function(response){ // response.on('data', (json) => {chunks.push(json);}); response.on('data', (json) => { }); // response.on('data', (json) => {chunks = buffer.concat([chunks ,json]); }) //if using chunks = new buffer(0) response.on('end',() => { var parsedjson = json.parse(buffer.concat(chunks).tostring()); // var parsedjson = json.parse(chunks.tostring()); parsedjson.items.foreach(function(item){ console.log(count+". "+item.snippet.title + " " + '\x1b[33m%s\x1b[0m:', item.contentdetails.itemcount + " videos"); fs.appendfilesync("message.txt",count+". "+item.snippet.title + " " + item.contentdetails.itemcount + " videos\n", {flags: 'a'}); count++; //labeling list }); }) }) }); });
changing response.on('data', (json) => { });
to
response.on('data', (json) => {chunks.push(json);});
to add next 50 playlist chunks
generate parsing error of unexpected token.
i have tried using var chunks = new buffer(0)
response.on('data', (json) => {chunks = buffer.concat([chunks ,json]); })
, var parsedjson = json.parse(chunks.tostring());
generates same unexpected token error, solved if 1 of 2 requests pushed chunks
.
printing chunks
after executing both requests shows 100 results (10 buffers) 2 requests formatted, can't figure out why chunks
has token errors when parse it.
Comments
Post a Comment