什么是PM2


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/10/02/%E4%BB%80%E4%B9%88%E6%98%AFPM2/

摘要

本文主要讲述了:

  1. 什么是 PM2
  2. 安装
  3. 示例

正文

什么是 PM2

PM2 是一个开源的 nodejs 进程管理器。

安装

全局安装

1
2
3
#!/usr/bin/env bash

npm install -g pm2

示例

learn_pm2/ecosystem.config.js

1
2
3
4
5
6
7
8
module.exports = {
apps: [
{
name: 'learn_pm2',
script: 'index.js',
},
],
};

learn_pm2/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const http = require('http');
const path = require('path');
const fs = require('fs');
const mime = require('mime');

const server = http.createServer();
const baseURL = 'html';

function get(req, res) {
const url = new URL(req.url, 'http://localhost');
const pathname = decodeURIComponent(url.pathname);
const filepath = path.join(__dirname, baseURL, pathname);
fs.stat(filepath, function (er, stat) {
if (er) {
if (er.code === 'ENOENT') {
res.statusCode = 404;
res.end('Not Found');
} else {
res.statusCode = 500;
res.end('Internal Server Error');
}
} else {
res.setHeader('Content-Type', mime.getType(filepath));
res.setHeader('Content-Length', stat.size);
const stream = fs.createReadStream(filepath);
stream.on('error', function () {
res.statusCode = 500;
res.end('Internal Server Error');
});
stream.pipe(res);
}
});
}

server.on('request', function (req, res) {
switch (req.method) {
case 'GET':
get(req, res);
break;
case 'POST':
break;
default:
break;
}
});

const hostname = process.argv[2] || '127.0.0.1';
const port = process.argv[3] || 3000;

server.listen({
hostname,
port,
});

console.log(`Server is running at http://${hostname}:${port}`);

启动:

1
2
3
#!/usr/bin/env bash

npx pm2 start

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/10/02/%E4%BB%80%E4%B9%88%E6%98%AFPM2/


本文对你有帮助?请支持我


支付宝
微信