NodeJS:ECMAScript
- 在nodejs中没有DOM和BOM
NodeJS多版本共存工具:nvm
- nvm version 查看版本
- nvm list 查看安装列表
- nvm install 安装node版本
- nvm uninstall 写在已安装的node版本
- nvm use 切换(使用)node版本
模块化:commonJS规范
-
引入:require()
查找策略: -
导出:
- module.exports(推荐)
- exports
模块化开发规范
- CommonJS node.js采用的规范
- CMD sea.js框架支持的规范
- AMD require.js框架支持的规范
- ESModule ES6推出的模块化规范
模块化开发的优点
- 更新迭代更容易
- 分工更容易
- 复用
模块分类
1.内置模块:nodejs自带的模块,可以直接引用
- http
- fs ==>file system
- url
- …
const fs=require('fs')
2.自定义模块:自己编写的符合commonJS规范的模块
const tools=require('./tools')
3.第三方模块:需要通过npm install
安装(安装到node_modules),安装完成可直接引用
const gulp=require('gulp')
利用http模块创建服务器
//server.js文件(有问题的版本)
const http=require('http');
//创建一个http服务器
http.createServer(function(req,res){
//req:请求对象
//res:响应对象
//设置状态码和响应头
res.writeHead(200,{
//'Content-Type':'text/html;chartset=utf-8'
'Content-Type':'text/plian;chartset=utf-8'
})
res.write('hello')
//结束响应
res.end('这里可以写内容也可以不写')
}).listen(2021,()=>{
console.log('服务器启动成功')
})
//node server 运行程序(不会自动监听,改了代码要重启)
//supervisor server (会自动监听,前提安装了supervisor)
//server.js文件(没问题的版本)
//根据不同的访问路径响应不同的内容
const http=require('http')
const fs=require('fs')
const path=require('path')
const mime=require('./mine')
const url=require('url')
const server=http.createServer((req,res)=>{
//获取访问路径
//console.log('url=',req.url)
const {pathname}=url.parse(req.url)//绝对路径
const realpath=path.join(__dirname,pathname)//后缀
const extname=path.extname(pathname).substring(1);
fs.readFile(realpath,(err,data)=>{
if(err){
res.writeHead(404,{"content-type":"text/plain;charset=utf-8"})
res.end('404')
return
}
res.writeHead(200,{'content-type':mime[extname]+';charset=utf-8'})
res.end(data)
})
})
server.listen(2101,()=>{
console.log('服务器启动成功')
})
静态资源服务器
静态资源:图片,js ,css ,html ,等文件
依赖模块
- http
- url
- path
- fs
mine类型
服务器告诉浏览器响应的内容类型(响应头:content-type)