NodeJS - http 服务

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.jsonpackage.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",

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值