gpt4 book ai didi

javascript - Node JS ctrl + C 不会停止服务器(使用 "npm start"启动服务器后)

转载 作者:IT老高 更新时间:2023-10-28 22:04:42 27 4
gpt4 key购买 nike

当我在命令行中使用 node app.js 启动服务器时(使用 Git Bash),我可以使用 ctrl + C 停止它。

在我的 package.json 文件中,我得到了这个启动脚本,它允许我使用命令 npm start 来启动服务器:

"scripts": {
"start": "node app"
},

当我这样做时,服务器正常启动:

$ npm start

> nodekb@1.0.0 start C:\Projects\nodekb
> node app.js

Server started on port 3000...

但是当我现在 ctrl + C 时,服务器并没有停止( Node 进程仍然保留在任务管理器中)。这意味着当我再次尝试执行 npm start 时出现错误,因为端口 3000 仍在使用中。

我正在关注 youtube 上的教程 (video with timestamp),当这家伙 ctrl + C 然后再次运行 npm start 时,它可以正常工作。

知道为什么我使用 ctrl + C 时我的服务器进程没有停止吗?

如果需要,我的 app.js 文件:

var express = require("express");
var path = require("path");

//Init app
var app = express();

//Load View Engine
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");

//Home Route
app.get("/", function(req, res) {
res.render("index", {
title: "Hello"
});
});

//Add route
app.get("/articles/add", function (req, res) {
res.render("add_article", {
title: "Add Article"
});
});

//Start server
app.listen(3000, function() {
console.log("Server started on port 3000...");
});

谢谢!

最佳答案

Ctrl + C 不会杀死服务器。该问题的解决方案是在 server.js 中使用以下代码段:

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

这对我有用。

您还可以查看 Graceful shutdown in NodeJS 中提到的其他解决方案

关于javascript - Node JS ctrl + C 不会停止服务器(使用 "npm start"启动服务器后),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44788982/

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