背景
补充学习下node知识,课程来自imooc
从node基础到web相关的基础知识,到最后任务管理系统实战。
技术栈:react+redux+mysql+express
个人学习笔记,如有侵权,会删除。
2022.1.19
发现黑马的nodejs讲的特别好,大家可以直接B站搜索学习
笔记
node基础
-
创建一个nodejs程序
//读取系统的cpu的信息 const os = require('os'); //获取当前系统的cpu数量 const cpus = os.cpus(); console.log(cpus.length); //获取内存的信息 //总内存,GB const total = os.totalmem(); console.log(total / 1024 / 1024 / 1024); //剩余内存,GB const free = os.freemem(); console.log(free / 1024 / 1024 / 1024); //web服务 //ajax->api->web server(nodejs) const http = require('http'); //创建服务实例 //req 请求对象 //res 响应对象 const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello'); }) server.listen(3000, '127.0.0.1', () => { //回调 console.log('服务启动了') }) //启动服务 //node 1-nodejs.js
- nodejs 和npm
js调用nodejs的api
npm 安装第三方包
v8 引擎
libuv开发包,异步io(文件读取,http请求),实现非堵塞;事件驱动
底层调用os
- nodejs 和npm
-
nodemon 监听文件变化,自动重启服务
node在启动前,会把所有文件解析掉,以此提高性能,效率。所以每次更新后,需要重新启动服务
优化:nodemon-
配置nodemon
-
修改 package.json 中的启动命令
{ "name": "node_p", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "nodemon ./2-nodemon.js", "start:node": "node ./2-nodemon.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "nodemon": "^2.0.15" } }
-
nodemon.js配置指定修改的文件
- 配置 指定 特殊watch 的文件{ "watch": [ "./2-nodemon.js" ] }
-
2-nodemon.js
const http = require('http') const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('hesslsl'); }) server.listen(3000, '127.0.0.1', () => { //回调 console.log('server 启动了') })
-
-
nrm和nvm
- nrm管理源,比如cnpm,在有些库不好下载,可以换源下载
1. 安装 npm i nrm -g
2. nrm ls
3. nrm current
4. nrm use taobao
5. nrm add xxx 自定义源 - nvm
- nvm ls remote --lts
- nvm install xxx
- nvm use xxx
- nvm ls
- nvm alias default node
- nvm -v
web基础
web基础
1. 前端(ajxs,ws,ws)->服务器(web应用)->缓存/数据库
2. express
1. 接收req,处理res
2. express:node中的一种web框架
3. express应用
1. npm init -y
2. git init
3. .gitignore (node_modules)
4. npm i express -s
5. src/app.js
6. 具体代码
```
const express = require('express');
//是一个express实例
const app = express();
// app.use((req, res) => {
// res.json({
// name: "sss"
// })
// })
app.get('/name/:age', (req, res) => {
//res.send('tom get')
let { age } = req.params;
res.json({
name: 'tom',
age
})
})
app.post('/name', (req, res) => {
res.send('tom post')
})
app.listen(3000, () => {
console.log('server ok')
})
```
路由
- 准备
1. git init 2. npm init -y 3. npm i nodemon -D 4. npm i express -S 5. package.json 里面添加 "start": "nodemon src/app.js",
实战:做一个任务管理项目