gpt4 book ai didi

node.js - NodeJS : need to obtain reference to existing server or to close it

转载 作者:太空宇宙 更新时间:2023-11-04 00:23:51 25 4
gpt4 key购买 nike

好吧 - 有些东西我找不到,但我觉得可能相当简单。我创建了一个服务器,但忘记捕获变量中发回的引用。

http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);

现在我正在尝试关闭服务器,但我没有对服务器的引用。有没有办法从nodejs解释器获取引用或关闭http服务器以避免使用taskmanager杀死进程。正在使用 Win 7 NodeJS 解释器。

不允许创建新的。

 const server = http.createServer(function(request, response) {
.. // Send the HTTP header
.. // HTTP Status: 200 : OK
.. // Content Type: text/plain
.. response.writeHead(200, {'Content-Type': 'text/plain'});
..
.. // Send the response body as "Hello World"
.. response.end('Hello World\n');
..
.. }).listen(8081, () => {
..
.. console.log("closing the server in 5 seconds");
..
.. setTimeout(() => server.close(), 5000);
..
.. });
ndefined
Error: listen EADDRINUSE :::8081
at Object.exports._errnoException (util.js:1012:11)
at exports._exceptionWithHostPort (util.js:1035:20)
at Server._listen2 (net.js:1252:14)
at listen (net.js:1288:10)
at Server.listen (net.js:1384:5)
at repl:10:4
at sigintHandlersWrap (vm.js:32:31)
at sigintHandlersWrap (vm.js:96:12)
at ContextifyScript.Script.runInContext (vm.js:31:12)
at REPLServer.defaultEval (repl.js:308:29)

最佳答案

您可以使用 server.close(); 关闭它或者直接使用 Ctrl-C 终止进程。

http.createServer返回服务器,因此将返回值分配给变量/常量,然后您可以引用服务器。

const server = http.createServer(function(request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"
response.end('Hello World\n');

}).listen(8081, () => {

console.log("closing the server in 5 seconds");

setTimeout(() => server.close(), 5000);

});

关于node.js - NodeJS : need to obtain reference to existing server or to close it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43592793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com