node.js能力
- 脱离浏览器运行js
- NodeJS Stream(前端工程化基础)
- 服务端API
- 作为中间层
第一段nodejs代码
安装node.js环境;打开vs code 新建文件夹island ;在该文件夹下新建test.js文件
function test(){
console.log("helloworld")
}
test()
打开终端,输入node test.js
运行代码
后端:主要读写数据库 提供API
安装koa2
在终端中输入npm -v
测试当前npm版本
npm init
初始化项目配置文件 一直回车选择默认配置
npm i koa
安装koa2
安装完成时候终端会显示+koa@2.x.x
导入导出方式
- commonJS
const var_name = require("xxx")
- ES6 import from(nodejs中暂时不支持)
- AMD
在文件夹下新建app.js
//app.js
const Koa = require('koa')
const app = new Koa()
//应用程序对象 中间件
//函数
function test(){
console.log("helloworld")
}
//注册
app.use(test)//接收到http请求之后调用use
app.listen(3000)//端口号
从前端发送请求到服务端:打开浏览器,输入localhost:3000
这时,终端打印出了helloworld
中间件一般来说我们使用箭头函数
app.use(()=>{
//匿名函数
console.log("helloworld")
})
app.use(()=>{
//匿名函数
console.log("helloworld1")
})
这样的话默认执行第一个中间件。其实koa给app.use提供了两个默认参数。
app.use((ctx,next)=>{//ctx为上下文,
//匿名函数
console.log("helloworld")
next()
})
app.use(()=>{
//匿名函数
console.log("helloworld1")
})
洋葱模型
app.use(async (ctx,next)=>{//ctx为上下文,
//匿名函数
console.log("1")
await next()
console.log("2")
})
app.use(async (ctx,next)=>{
//匿名函数
console.log("3")
await next()
console.log("4")
})
//如果不加async和await,不能保证所有的中间件都是按洋葱模型执行的
我们可以看到打印到终端的顺序为 1 3 4 2
app.use((ctx,next)=>{//ctx为上下文,
//匿名函数
console.log("1")
const a = next()
console.log(a)
console.log("2")
})
由结果可知,next()返回的结果是一个Promise。
async和await必须搭配使用。
await相当于一个求值关键字,await加任意一个表达式,都可以对这个表达式求值。
app.use(async(ctx,next)=>{//ctx为上下文,
//匿名函数
console.log("1")
const a =await next()
/* a.then((res)=>{
console.log(res)
}) */
console.log(a)
console.log("2")
})
app.use((ctx,next)=>{
//匿名函数
console.log("3")
//next()
console.log("4")
return "abc"
})
阻塞线程
app.use(async (ctx,next)=>{
const anxios = require('axios')
const start = Date.now()
const res = await anxios.get("http://7yue.pro")
const end = Date.now()
console.log(end-start)
//next() 对资源 读文件 发送http请求 操作数据库等都是异步的
})
不加async和anxious时,end-start的值为0,而加上之后,值为896。阻塞当前线程,等待这次异步调用结果的返回。中间件传参时将接受参数的变量放在next后,就能保证后面的中间件全部执行完成(如果不按照洋葱模型,则无法保证)。