什么是nodemon


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/07/30/%E4%BB%80%E4%B9%88%E6%98%AFnodemon/

摘要

本文主要讲述了:

  1. 作用
  2. 安装
  3. 示例

正文

作用

监听项目文件变更并重启 nodejs 应用。

安装

局部安装

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

npm install --save-dev nodemon

示例

learn_nodemon/package.json

1
2
3
4
5
6
7
8
9
10
11
{
"name": "learn_npm",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {
"nodemon": "^1.19.2"
},
"dependencies": {
"mime": "^2.4.4"
}
}

learn_nodemon/nodemon.json

1
2
3
{
"watch": ["index.js"]
}

learn_nodemon/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 nodemon index.js

当 CWD 下的index.js变更时,nodemon 会结束原先的 nodejs 进程并执行node index.js

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/07/30/%E4%BB%80%E4%B9%88%E6%98%AFnodemon/


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


支付宝
微信