Reputation: 1523
I’m new to Node.js, and so sorry for what is probably a dumb question…
Here’s my code:
#!/usr/bin/env coffee --bare
# 3rd party
request = require('request')
request.defaults({'encoding': 'utf8'})
module.exports.fetchDepartments = fetchDepartments
fetchDepartments = (url) ->
_body = ''
getHandler = (error, response, body) ->
util.debug "HTTP response code: #{response.statusCode}"
if error
util.error error
else
_body = body
request.get(url, getHandler)
_body
console.log fetchDepartments('https://ntst.umd.edu/soc/')
The console is printing the call to util.debug()
, but it seems that _body
remains an empty string.
…How can I store the HTML from the HTTP response?!?
Upvotes: 1
Views: 2028
Reputation: 12882
You seem to be returning the _body
before the request is completed.
The request is not synchronous, so you'll almost certainly want to define a callback instead. In plain JavaScript, that would be:
fetchDepartments('https://ntst.umd.edu/soc', function (err, body) {
console.log(body);
});
What it's currently doing is:
_body
to ''
getHandler
_body
_body
getHandler
getHandler()
updates _body
What you need to do is to make fetchDepartments
accept callback function, so that whatever code processes _body
can wait until the request is complete.
Upvotes: 2