Node JS ctrl + C 不会停止服务器(使用“npm start"启动服务器后) [英] Node JS ctrl + C doesn't stop server (after starting server with "npm start")

查看:215
本文介绍了Node JS ctrl + C 不会停止服务器(使用“npm start"启动服务器后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I start my server with node app.js in the command line (using Git Bash), I can stop it using ctrl + C.

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

In my package.json file i got this start-script that allows me to use the command npm start to start the server:

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

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

When I do this, the server starts as normal:

$ npm start

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

Server started on port 3000...

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

But when i ctrl + C now, the server does not get stopped (the node process still remains in task manager). This means that I get an error when I try to do npm start again, because port 3000 is still being used.

我正在关注 youtube 上的教程(带时间戳的视频),当这个家伙ctrl + C 然后再次运行npm start,就正常了.

I'm following a tutorial on youtube (video with timestamp), and when this guy ctrl + C and then runs npm start again, it works as normal.

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

Any ideas why my server process is not stopped when I use ctrl + C?

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

My app.js file if needed:

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 中使用以下代码片段:

Ctrl + C does not kill the server. The resolution to the issue was using following code snippet in server.js:

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

这对我有用.

您还可以查看 NodeJS 中的正常关闭

这篇关于Node JS ctrl + C 不会停止服务器(使用“npm start"启动服务器后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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