如何知道node.js express服务器何时启动并准备使用 [英] How to know when node.js express server is up and ready to use

查看:112
本文介绍了如何知道node.js express服务器何时启动并准备使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个应用程序,我想启动一个节点express服务器,然后一旦服务器启动,就自动启动浏览器在同一台机器上。如何查询服务器是否启动并准备好了?我真的希望在.listen电话上有一些回调,但似乎不是。我可以等待一段时间超过我预期的时间,但这是在现场的设备上,所以我不得不等待一个可笑的时间,以确保我开始运行,然后开始浏览器或者如果页面没有加载正确,请让用户足够聪明地点击刷新。这两个都不是我的好选择。 。 。



我在线阅读API,但没有看到这样的东西。确实有一个技巧我不知道可以实现这一点。



如果节点HTTP api(有一个回调并告诉我关于监听事件)是基地对于明确的对象,也许有一个没有记录的express call的回调选项。或者也许我应该知道它在那里。



任何帮助将不胜感激。

解决方案

Express app.listen 功能 支持回调。它将您传入的参数映射到http.listen调用。

  app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server,arguments);
};

所以你可以打电话: app.listen(port,callback);



或者您可以直接使用http.listen。

 code> var app = require('express')(),
server = require('http')。createServer(app);

server.listen(80,function(){
console.log('ready to go!');
});


Have an application where I want to start a node express server and then start a browser on the same machine automatically as soon as the server is up. How can I query to see if the server is up and ready to go? I really wanted there to be some sort of callback on the .listen call, but doesn't seem to be. I could just wait a longer than I expect amount of time, but this is going on equipment that will be in the field so I either have to wait a ridiculous amount of time to make sure I'm up and running before kicking off the browser or have the user be smart enough to hit refresh if the page doesn't load right. Neither of those are good options for me. . .

I read the API online but don't see anything like this. Surely there's a trick I don't know that can accomplish this.

If the node HTTP api (which has a callback and tells me about the listening event) is the base for the express object, maybe there is a callback option for the express call listen that isn't documented. Or perhaps I'm supposed to just know that it's there.

Any help would be greatly appreciated.

解决方案

The Express app.listen function does support a callback. It maps the arguments that you pass in to the http.listen call.

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

So you can just call: app.listen(port, callback);

Or you could use http.listen directly.

var app = require('express')(),
    server = require('http').createServer(app);

server.listen(80, function() {
    console.log('ready to go!');
});

这篇关于如何知道node.js express服务器何时启动并准备使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆