node.js 以编程方式停止和重新启动快速服务器(以更改端口)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9959590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically stop and restart express servers (to change ports)
提问by Matt
I'm looking to be able to basically change ports that my express app is running on.
我希望能够基本上更改我的 Express 应用程序正在运行的端口。
I've tried:
我试过了:
server.on('close', function() {
server.listen(3000);
});
server.listen(8080);
server.close();
This returns a cryptic node.js error. I'm running node v0.4.11, I'm upgrading now to see if that fixes it.
这将返回一个神秘的 node.js 错误。我正在运行 node v0.4.11,我现在正在升级以查看是否可以修复它。
EDITHere's the error:
编辑这是错误:
Assertion failed: (!io->watcher_.active), function Set, file ../src/node_io_watcher.cc, line 160.
Thanks, Matt
谢谢,马特
回答by loganfsmyth
The issue is that .listenis asynchronous. By calling .closeimmediately after calling .listen, you are closing it before it has been opened.
问题是这.listen是异步的。通过在调用.close之后立即调用.listen,您将在它被打开之前关闭它。
Try this instead.
试试这个。
server.listen(8080, function() {
server.close();
});
回答by Derek Hill
Thanks to @aymericbeaumet, the following snippet works with Express 4:
感谢@aymericbeaumet,以下代码段适用于 Express 4:
var app = express();
var server = app.listen(8080, function() {
console.log('Listening :)');
server.close(function() { console.log('Doh :('); });
});

