0

我写了一些服务器端代码,应该从雅虎获取实时数据,然后在我运行服务器时将其打印到控制台和浏览器,问题是我找不到打印到文档的函数请求块。这是我的代码:

var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
var util = require('util');

tempvar = null;
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();
    testTemp = null;

    //
    // 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();
            console.log("Stock  - " + ticker + " --> text " + stockValue);
            //res.write("Stock  - " + ticker + " --> text " + stockValue);
            testTemp = stockValue;
// 

-- end of request --
        res.write("Stock value for: " + ticker + " is --> " + testTemp + "\n");
        res.write("12333\n");
        res.write('something\n');

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

## Heading ##
        }

    }); 

});

server.listen(1400, '127.0.0.1');

这是我在控制台 Files\node.js\node_modules\YfTemp.js:49 >>; SyntaxError:Module._compile 在 Object.Module._extensions..js 在 Module.load 在 Function.Modul._load 在 Function.Module.runMain 在 node.js:906:3 的输入意外结束

4

1 回答 1

3

Request异步工作。您需要将脚本的打印部分放在请求回调块中。否则,ticker到达打印行时尚未定义。

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();
        console.log("Stock  - " + ticker + " --> text " + stockValue);
        //res.write("Stock  - " + ticker + " --> text " + stockValue);
        testTemp = stockValue;

        // -- end of request --
        res.write("Stock value for: " + ticker + " is --> " + testTemp + "\n");
        res.write("12333\n");
        res.write('something\n');

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

     }


});
于 2014-08-12T15:02:37.837 回答