运行node Server.js后如何关闭? - 网站

运行node Server.js后如何关闭?

分类:Node.js常见问题 · 发布时间:2019-08-05 16:12 · 阅读:3148

运行node Server.js后关闭的方法:在命令行使用Ctrl+c即可退出node server,或使用exit命令直接退出node命令也可以关闭server.js。下面本篇文章就来具体介绍一下,希望对大家有所帮助。

如果是要退出node命令的话,可以使用:

1 (2).jpg-600

js代码:

$ node  
> 9+23  
32  
> process.exit()  
$

$ node  
> 9+23  
32  
> .exit  
$

如果是要退出node server的话,可以使用:

2.jpg-600

3.jpg-600

别人是推荐点击两下 Ctrl-C, 但是我使用的时候不好使,不知道是不是因为需要大写的C才行,所以我使用 Ctrl-Shift-C 的时候就可以了,不过这个快捷键需要结合下面的代码使用:

// this function is called when you want the server to die gracefully
// i.e. wait for existing connections
var gracefulShutdown = function() {
  console.log("Received kill signal, shutting down gracefully.");
  server.close(function() {
    console.log("Closed out remaining connections.");
    process.exit()
  });
  
   // if after 
   setTimeout(function() {
       console.error("Could not close connections in time, forcefully shutting down");
       process.exit()
  }, 10*1000);
}

// listen for TERM signal .e.g. kill 
process.on ('SIGTERM', gracefulShutdown);

// listen for INT signal e.g. Ctrl-C
process.on ('SIGINT', gracefulShutdown);

全部的代码为:

var express = require('express');
var app = express();

// listen on the specified port
var server = app.listen(8080);

// serve out content
app.get('/', function(req, res){
  var body = 'Hello World';
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Content-Length', body.length);
  res.end(body);
});

// this function is called when you want the server to die gracefully
// i.e. wait for existing connections
var gracefulShutdown = function() {
  console.log("Received kill signal, shutting down gracefully.");
  server.close(function() {
    console.log("Closed out remaining connections.");
    process.exit()
  });
  
   // if after 
   setTimeout(function() {
       console.error("Could not close connections in time, forcefully shutting down");
       process.exit()
  }, 10*1000);
}

// listen for TERM signal .e.g. kill 
process.on ('SIGTERM', gracefulShutdown);

// listen for INT signal e.g. Ctrl-C
process.on ('SIGINT', gracefulShutdown);

因为点击Ctrl-Shift-C之后就会触发process函数。

4.jpg-600

Ctrl-z 之后,使用

ps aux | grep node
kill -9 PID

标签:
node

相关文章

如何设置 nodejs 的环境变量

在前端开发过程中,我们需要对 application 运行的环境进行设置,一般会包括开发环境development,生产环境production,每个环境可以对应不同的一些配置,例如不同环境下请求的地址...

谈谈Node.js与JavaScript的差异

Javascript是一种web前端语言,主要用于web开发中,由浏览器解析执行。Node.js是一个可以快速构建网络服务及应用的平台,是用Javascript语言构建的服务平台。

npm install安装报错怎么解决?

解决方法:1、报“operation not permitted”错误,通过“npm i 包名 --no-optional”解决;2、报“Missing: chromedriver”错误,表示没有安装chromedriver,安装一下即可。

怎么使用npm下载vue.js?

使用npm下载vue.js的方法:1、安装node.js和npm;2、安装cnpm;3、使用命令cnpm install -g vue-cli来安装即可。

vue.js和node.js是什么关系?

vue.js和node.js并没有关系,vue.js是前端框架,算是js的三大框架之一吧,node.js是后端开发语言,同php、java、c#一样的。但是他们可以配合使用。

返回分类 返回首页