如何在请求模块中进行response.write

时间:2014-08-16 16:18:18

标签: javascript node.js http npm

我正在创建HTTP服务器,我正在向雅虎金融网站发送请求并从中获取一些数据,我想要做的是打印浏览器从雅虎财务获得的数据。 问题是response.write在请求中没有工作。 这是我的代码:

    var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
var util = require('util');
var host  = "127.0.0.1";
var port = 1400;

var server = http.createServer(function (req, res) {
  //writing the headers of our response
  res.writeHead(200, {'Content-Type':'text/plain'});

  // Variable Deceleration 
// TODO: move from the global scope
var ticker  = "IBM";
var yUrl    = "http://finance.yahoo.com/q/ks?s=" + ticker;
var keyStr  = new Array();

//
// The main call to fetch the data, parse it and work on it.  
//
request(yUrl, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var $ = cheerio.load(body);


    // the keys - We get them from a certain class attribute
    var span = $('.time_rtq_ticker>span');
    stockValue = $(span).text();
    res.write("trying to print something");
    console.log("Stock  - " + ticker + " --> text " + stockValue );  
      }

}); // -- end of request --



    res.write('Welcome to StockWach\n');

  //printing out back to the client the last line
    res.end('end of demo');


});

server.listen(port, host, function () {
    console.log("Listening : " + host +":" + port);
});

1 个答案:

答案 0 :(得分:1)

您必须结束回复(res.end();)。在显示任何内容之前,几乎所有浏览器都会从响应中缓冲一些字节数,因此在响应结束之前,您将无法看到trying to print something

如果您使用类似cURL的内容,您会在响应结束前立即看到trying to print something