I have been playing around with the youtube API and node.js, so far I have been able to get a response from the API and console.log
it onto the terminal.
When I try to get the response and use JSON.parse
, I get a weird error:
Got response: 200
undefined:1
http://www.w3.or
^
SyntaxError: Unexpected token u
at Object.parse (native)
at IncomingMessage.<anonymous> (/home/ubuntu/node_temp4/index.js:19:10)
at IncomingMessage.emit (events.js:88:20)
at HTTPParser.onMessageComplete (http.js:137:23)
at Socket.ondata (http.js:1137:24)
at TCP.onread (net.js:354:27)
This is my script:
var http = require("http");
var searchQuery = "cats";
var queryResponse;
var options = {
host: 'gdata.youtube.com',
path: "/feeds/api/videos?q=" + searchQuery + "&max-results=1&v=2&alt=json"
};
http.get(options, function(response) {
console.log("Got response: " + response.statusCode);
response.on('data', function(chunk){
queryResponse += chunk;
});
response.on('end', function(){
JSON.parse(queryResponse);
console.log('end');
});
}).end();
parse() itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code. If you force code into a JSON object with a string, you must use the Javascript eval() function to convert it into something the Javascript interpreter understands.
So yes it JSON. parse blocks. Parsing JSON is a CPU intensive task, and JS is single threaded. So the parsing would have to block the main thread at some point.
Exceptions. Throws a SyntaxError exception if the string to parse is not valid JSON.
The variable queryResponse
is set to undefined
and you are doing queryResponse += chunk
in the 'data' envent handler which means queryResponse = queryResponse + chunk
so you get
undefined{"youtube":["Api", "response"]}
you can fix it by instantiating queryResponse
as an empty string var queryResponse = ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With