Node.js:服务器等待响应和超时

时间:2011-11-04 22:48:33

标签: javascript node.js

如何改进对iSpeech的这个GET请求,以便当它发出请求时,服务器在iSpeech需要一些时间返回时不会超时。

app.get("/", function(req, res) {
    var url;
    if (req.param("url")) {
      url = unescape(req.param("url"));
      return request({
        uri: url,
        encoding: "binary"
      }, function(error, response, body) {
        var audio, format;
        if (!error && response.statusCode === 200) {
          format = response.headers["content-type"];
          audio = new Buffer(body.toString(), "binary");
          return request.post({
            headers: {
              "content-type": format
            },
            url: ispeech_server,
            body: audio
          }, function(error, response, body) {
            var parse;
            if (!error && response.statusCode === 200) {
              parse = querystring.parse(body);
              return res.send(parse, {
                "Content-Type": "application/json"
              }, 500);
            } else {
              return res.send("Error - iSpeech API returned an error", {
                "Content-Type": "text/plain"
              }, 500);
            }
          });
        } else {
          return res.send("Invalid URL - File Not Found", {
            "Content-Type": "text/plain"
          }, 404);
        }
      });
    } else {
      return res.send("Invalid URL - File Not Set", {
        "Content-Type": "text/plain"
      }, 404);
    }
  });

1 个答案:

答案 0 :(得分:0)

使用.timeOut()功能。