我编写了一个node.js服务器,它创建了一个服务器并在完成异步函数时打印输出。虽然我总能在console.log中获得正确的输出。同样没有反映在我的回答中。这是我的代码片段: -
var request = require('request');
var http = require('http');
var cheerio = require('cheerio');
var url = require('url');
var Curl = require( 'node-libcurl' ).Curl;
var sleep = require('sleep');
isDone = 0;
globalImage = "";
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var main_url = query["link"];
if (req.url != '/favicon.ico') {
res.writeHead(200);
if(main_url != undefined ){
var position = parseInt(query["position"]);
// web_scrap()
web_scrap(main_url,position, function(image) {
console.log("Console log : " + image);
globalImage = image;
});
res.write(globalImage);
res.end("HEY");
}
}
else {//For favicon and other requests just write 404s
res.writeHead(404);
res.write('This URL does nothing interesting');
res.end();
}
}).listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');
function web_scrap(url, position, callback){
// do something
callback(JSON.stringify(product));
}
现在启动服务器并在浏览器中使用参数链接和位置作为get访问它,我在第二次或第三次刷新时获得输出。我在console.log中获得了完美的输出!
在这方面,有人可以帮助或指导我吗?
谢谢!
答案 0 :(得分:2)
据我所知,你是异步加载来自外部源的图像。
因此,即使负载尚未完成,您的功能仍会继续运行。并且由于globalImage
是一个全局变量,一旦加载,它就会保留在内存中,这就是你在一些尝试后得到数据的原因。
只需将res.write和res.end移动到回调函数中,这样就可以在加载图像后发送内容。
web_scrap(main_url,position, function(image) {
console.log("Console log : " + image);
globalImage = image;
res.write(globalImage);
res.end("HEY");
});
无论如何,除非你想要缓存你的图像,否则你不应该有一个globalImage
变量,因为它会保留在内存中,即使你希望它被垃圾收集。您可以删除变量,只需执行以下操作:
web_scrap(main_url,position, function(image) {
console.log("Console log : " + image);
res.write(image);
res.end("HEY");
});