W1_NodeJS

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. 更新迭代更容易
  2. 分工更容易
  3. 复用

模块分类

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)

内置模块

http模块
url模块
path模块
fs模块
events模块
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值