1

I’m new to Node.js, and so sorry for what is probably a dumb question…</p>

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?!?

4

1 回答 1

2

您似乎在请求完成_body 之前返回。

该请求不是同步的,因此您几乎可以肯定要定义一个回调。在纯 JavaScript 中,这将是:

fetchDepartments('https://ntst.umd.edu/soc', function (err, body) {
    console.log(body);
});

目前正在做的是:

  1. 初始化_body''
  2. 创建(但不执行!)getHandler
  3. 开始请求
  4. 返回(仍然为空)_body
  5. 记录(空)_body
  6. 稍后:请求完成,调用getHandler
  7. getHandler()更新_body

您需要做的是制作fetchDepartments接受回调函数,以便任何代码进程_body都可以等到请求完成。

于 2013-11-01T17:03:36.107 回答