3

我正在尝试运行一个简单的应用程序,该应用程序使用 http 服务器模块检查 URL 的状态。

基本上这是一个简单的 http 服务器:

require('http').createServer(function(req, res) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end('URL is OK');
    }).listen(4000);

现在,我想使用此部分检查 URL 的状态:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log("URL is OK") // Print the google web page.
  }
})

所以基本上我想启动 node ,打开浏览器并显示带有“URL OK”文本的内容。然后每10分钟刷新一次。

任何帮助是极大的赞赏。

4

1 回答 1

13

使用节点的一般策略是,您必须在回调中放置任何取决于异步操作结果的内容。在这种情况下,这意味着等待发送您的回复,直到您知道 google 是否启动。

为了每 10 分钟刷新一次,您需要在所服务的页面中编写一些代码,可能使用<meta http-equiv="refresh" content="30">(30s) 或Preferred method to reload page with JavaScript? 中的一种 javascript 技术?

var request = require('request');
function handler(req, res) {
  request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log("URL is OK") // Print the google web page.
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end('URL is OK');
    } else {
      res.writeHead(500, {'Content-Type': 'text/html'});
      res.end('URL broke:'+JSON.stringify(response, null, 2));
    }
  })
};

require('http').createServer(handler).listen(4000);
于 2013-09-27T13:02:24.657 回答