Is there an end event when using the request module?
Problem
I am using the Request Module that found on npm, and I am wondering if there is an end event that i can bind to. The reason i'm asking is because i am requesting a JSON and i am getting an error if i try to use JSON.parse directly after i get the response. The code looks something like this.
var parseJSON = function(JSON, cb){
var parsed = JSON.parse(JSON);
cb(parsed);
};
request(url, function(error, response, body) {
parseJSON(body, function(bodyObj){
// do stuff with bodyObj...
});
});
Trying to do this, gives the following error...
var parsed = JSON.parse(JSON);
^
has no method 'parse'
at parseJSON (/home/stephen/Desktop/redditjs/reddit.js:31:20)
at Requester.collector [as _callback] (/home/stephen/Desktop/redditjs/reddit.js:43:5)
at Request.init.self.callback (/home/stephen/node_modules/request/main.js:122:22)
at Request.EventEmitter.emit (events.js:99:17)
at Request. (/home/stephen/node_modules/request/main.js:661:16)
at Request.EventEmitter.emit (events.js:126:20)
at IncomingMessage.Request.start.self.req.self.httpModule.request.buffer (/home/stephen/node_modules/request/main.js:623:14)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23
Problem courtesy of: Wiggles
Solution
The issue is that you're overriding the global JSON object.
This will work just fine:
var parseJSON = function(MyJSON, cb){
var parsed = JSON.parse(MyJSON);
cb(parsed);
};
Solution courtesy of: trebuchet
Discussion
View additional discussion.