这是我参与「第五届青训营 」伴学笔记创作活动的第7天
概述
本节课程主要分为四个方面:
- 介绍 Node.js 的应用场景
- 介绍 Node.js 运行时结构
- 如何用编写 Http Server
- 延伸话题
课前
- 安装 Node.js。可以选择以下一种方式:
- 从 Node.js 官网安装 nodejs.org/en/
- Mac, Linux 环境可以使用 nvm 进行安装 github.com/nvm-sh/nvm
- NVM_NODEJS_ORG_MIRROR=npmmirror.com/mirrors/nod… nvm install 16
什么是node.js
是一个基于chrome V8 引擎javascript运行环境,在node.js中无法调用DOM、BOM等浏览器内置API,node.js提供了其他API使用
文件系统模块
使用require导入模块,可以读取指定文件内容,向文件中写入内容
读取方法
- 参数一,必选,为字符串型,表示文件的路径
- 参数二,可选,表示用什么编码来读取文件
- 参数三,必选,文件读取完,通过回调函数拿到读取的结果,参数err是失败后传给的参数,dataStr是成功后给的值
写入方法
- 参数一,必选,表示文件路径
- 参数二,必选,表示要写入的内容
- 参数三,可选,表示以什么格式写入,默认是utf8
- 参数四,必选,文件写入完成后的回调函数,errerr是写入失败的给的值,如果成功则是nullnull
HTTP Server
const port = 3000
const server = http.createserver((req,res)=> {
res.end( 'hello ')
})
server.listen(port,()=> {
console.log( 'server listens on: ${port}`)
})
HTTP Client
const body = JSON.stringify({ msg: 'hello from my client' })
const req = http.request( 'http://127.0.0.1:3000' , {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': body.length,
},
}, (res) => {
const bufs = []
res.on('data', data => {
bufs.push(data)
})
res.on('end',()=> {
const receive = JSON. parse(Buffer.concat(bufs).toString())
console.log( 'receive:', receive)
})
})
req.end (body)
静态资源
const fs = require('fs')
const path = require('path')
const url = require('url")
const port = 3000
const server = http.createserver(( req, res) => {
const info = url.parse( req.url)
const file = fs.createReadStream(path.resolve(__dirname,'.' + info.pathname))
file.pipe(res)
})
server.listen(port,()=> {
console.log( 'server listens on: ${port} `)
})
课后
- 了解并尝试使用更多 Node.js 的原生模块 nodejs.org/dist/latest…
- 学习在 npm 上搜索并安装模块 www.npmjs.com/