NodeJS - http 服务
文章目录
1、编写服务
const http = require('http');
const server = http.createServer((req, res)=>{
res.end('hello')
})
server.listen(3000, '127.0.0.1', ()=>{
console.log('服务启动成功');
})
2、配置启动脚本
在 json 的 scripts
中添加 "start":"node src/app.js"
修改后结构如下:
{
"name": "demo0423",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start":"node src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
3、在项目文件夹下启动 npm start
% cd /Users/user/repos/CPPNotes/NodeJS/demos/demo0423
% npm start
> demo0423@1.0.0 start /Users/user/repos/CPPNotes/NodeJS/demos/demo0423
> node src/app.js
服务启动成功
4、使用 nodemon 自动重启
代码执行时,不会重新解析文件。
4.1 安装配置 nodemon
% npm install nodemon -D
> nodemon@2.0.3 postinstall /Users/user/node_modules/nodemon
> node bin/postinstall || exit 0
Love nodemon? You can now support the project via the open collective:
> https://opencollective.com/nodemon/donate
npm WARN saveError ENOENT: no such file or directory, open '/Users/user/package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open '/Users/user/package.json'
npm WARN user No description
npm WARN user No repository field.
npm WARN user No README data
npm WARN user No license field.
+ nodemon@2.0.3
added 121 packages from 58 contributors and audited 156 packages in 25.538s
7 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
4.2 修改 启动命令
"start":"nodemon src/app.js",
改完后
{
"name": "demo0423",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start":"nodemon src/app.js",
"start:node":"node src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
4.3、配置 nodemon.json
创建 nodemon.json
和 package.json
同一级别;会自动设置需要观测的文件
{
"watch":["./src/**/*.*"] // src 下的任何文件夹下的任何文件
}
需要重启;重启后,会发现 watching
的文件也改变了
% npm start
> demo0423@1.0.1 start /Users/user/repos/CPPNotes/NodeJS/demos/demo0423
> nodemon src/app.js
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node src/app.js`
服务启动成功
[nodemon] restarting due to changes...
[nodemon] starting `node src/app.js`
服务启动成功
4.4 Debug 模式
start 中添加 DEBUG=*
可以设置为 debug 模式,将会看到更多详细的日志信息;
"start":"DEBUG=* nodemon src/app.js",