node.js - 优雅地退出 node.js

标签 node.js

我正在阅读优秀的在线书籍 http://nodebeginner.org/并尝试简单的代码

var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888); 

现在我不知道(我仍然不知道!)如何优雅地关闭 node.js,所以我只是去了 ctrl+z。现在每次我尝试运行 node server.js 时都会收到以下错误消息。

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: EADDRINUSE, Address already in use
    at Server._doListen (net.js:1100:5)
    at net.js:1071:14
    at Object.lookup (dns.js:153:45)
    at Server.listen (net.js:1065:20)
    at Object.<anonymous> (/Users/Bob/server.js:7:4)
    at Module._compile (module.js:402:26)
    at Object..js (module.js:408:10)
    at Module.load (module.js:334:31)
    at Function._load (module.js:293:12)
    at Array.<anonymous> (module.js:421:10)

那么,两个问题:

1) 如何优雅地关闭 node.js?

2) 如何修复我造成的困惑?

最佳答案

我目前使用 Node 的事件系统来响应信号。以下是我在程序中使用 Ctrl-C (SIGINT) 信号的方法:

process.on( 'SIGINT', function() {
  console.log( "\nGracefully shutting down from SIGINT (Ctrl-C)" );
  // some other closing procedures go here
  process.exit( );
})

您收到“正在使用的地址”错误,因为 Ctrl-Z 不会终止程序;它只是暂停了类 Unix 操作系统上的进程,而您放置在后台的 Node 程序仍然绑定(bind)到该端口。

On Unix-like systems, [Control+Z] is the most common default keyboard mapping for the key sequence that suspends a process (SIGTSTP).[3] When entered by a user at their computer terminal, the currently running foreground process is sent a SIGTSTP signal, which generally causes the process to suspend its execution. The user can later continue the process execution by typing the command 'fg' (short for foreground) or by typing 'bg' (short for background) and furthermore typing the command 'disown' to separate the background process from the terminal.1

您需要通过执行 kill <pid> 来终止您的进程。或'killall -9 node'之类的。

关于node.js - 优雅地退出 node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6958780/

相关文章:

json - NodeJS JSON.parse 中缺少异常信息

node.js - 我可以要求 'require' 从我的应用程序根目录中搜索模块吗?

javascript - 当我在 Node JS 中调用 Modernizr.build 时,范围行为非常不寻常

mysql - Node.js连接失败,无法连接到RabbitMQ

javascript - 如何包装异步包函数?

node.js - Node child_process execSync 因 xclip 而挂起

javascript - 删除重复的错误处理代码Node.js

mysql - 使用nodejs和数据库存储GPS纬度和经度的最佳方式

javascript - 如何在谷歌云功能中从快照创建磁盘 - Node js

sql - TypeORM - 如何删除最后添加的行?