【问题标题】:Node js working on second or third call节点 js 处理第二次或第三次调用
【发布时间】:2014-06-06 12:18:34
【问题描述】:

我编写了一个 node.js 服务器,它创建一个服务器并在使用异步函数完成时打印输出。虽然我能够始终在 console.log 中获得正确的输出。我的回复中也没有反映出这一点。这是我的代码 sn-p :-

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 中得到了完美的输出!

任何人都可以在这方面帮助或指导我吗?

谢谢!

【问题讨论】:

  • 您尝试添加res.writeHead(200, {'Connection': 'Keep-Alive'}); 吗?
  • 我现在试过了。还是不行:(
  • 嗯,我认为这是由web_scrap中的异步调用引起的,这使得您的res.end函数之前被调用,尝试在您的回调函数中移动res.write(globalImage); res.end("HEY");
  • @JulienFouilhé 谢谢!它对我有用:) 我也以​​某种方式得到了一个空回调。所以,我检查了产品不为空,然后它工作了!

标签: javascript node.js http node-libcurl


【解决方案1】:

据我了解,您是从外部源异步加载图像。

因此,即使加载尚未完成,您的函数也会继续运行。由于您的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");
});

【讨论】:

    猜你喜欢
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多