我写了一些服务器端代码,应该从雅虎获取实时数据,然后在我运行服务器时将其打印到控制台和浏览器,问题是我无法找到功能即从请求块打印到文档。 这是我的代码:
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>&gt ;; SyntaxError:Module._compile中意外的输入结束 位于Function.Modul._load的Module.load的Object.Module._extensions..js位于函数.Module.runMain位于node.js的strartup:906:3
答案 0 :(得分: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');
}
});