浏览器是JavaScript的前端运行环境,node.js是JavaScript的后端运行环境。他们都包含V8引擎。
读取文件
fs.readFile(读取文件路径[,编码格式],callback)
const fs = require('fs');
fs.readFile('files/1.txt','utf8',function(err,dataStr){
console.log(err);
console.log("————————————");
console.log(dataStr);
})
终端输出结果:
null
————————————
0715
写入文件
fs.writeFile(读取文件路径,参数[,编码格式],callback)
参数是要写入的数据。
注意:这样写入是覆盖式写入!原文件内容会被覆盖
path模块 可以通过join拼接路径
http模块 创建web服务器
http模块的使用
//引入HTTP模块
const http = require('http');
//创建web服务器实例
const server = http.createServer();
//绑定request事件
server.on('request',(req,res)=>{
console.log("有人来了库啵");
const url = req.url;//用户请求的url地址
const method = req.method;//get或者post
const str = `your url is ${url},your request method is ${method}.`
console.log(str);
})
//启动服务器
server.listen(81,()=>{
console.log("滴滴……服务启动成功……");
})
向客户端发送数据并结束这次请求 res.end(data);
中文乱码问题
在返回数据之前的位置,添加响应头
res.setHeader('Content-Type','text/html; charset=utf-8');
res.end(str);
模块化
通过require方法,可以引入内置模块、自定义模块(通过路径添加)、第三方模块,注意,当引入模块时,会执行模块中的代码!
模块作用域
模块中的变量、方法不能被外部访问到,防止全局变量污染。
Q:但需要共享变量、方法时该怎么办?
A:使用module对象
module对象
在默认情况下,module.exports为空,在外界使用require导入自定义模块时,引入的就是exports的内容
const m = require('./excTest.js');
console.log(m);
控制台输出:
PS D:\vscode\workspace\nodejs> node .\moduleTest.js
{}
在exports上挂载要传递的内容
module.exports.username = "张三";
module.exports.sayHi = function(){
console.log('hello!!!');
}
控制台输出:
PS D:\vscode\workspace\nodejs> node .\moduleTest.js
{ username: '张三', sayHi: [Function (anonymous)] }
每个模块内部,module代表当前模块
npm包
包和node内置模块的关系类似jQuery和webAPI
全球最大的包共享平台npmjs
在上面网站搜索需要的包,在这里下载
包的分类
项目包->开发依赖包(只在开发时使用),核心依赖包
全局包
下载包
npm install 包的完整名称@版本
install可以省略为 i,@版本可以省略
末尾加-D
,代表这个包是开发依赖包
末尾加-g
,代表这个包是全局包
在一般的项目开发中,要把node_modules文件夹加入git的忽略文件,因为体积太大了
创建自己的包
①在新建文件夹下创建package.json(包管理配置文件)、index.js(入口文件)、README.md
②初始化package.json
{
"name": "gshtml",
"version": "1.0.0",
"main": "index.js",
"description": "格式化html",
"keywords": ["html","escape"],
"license": "ISC"
}
③在index.js中书写方法
function gshtml(str){
return str.replace(/<|>|&|"/g,(match)=>{
switch (match) {
case "<":
return "<"
case ">":
return ">"
case '"':
return """
case "&":
return "&"
}
})
}
//把方法加入exports
module.exports = {
gshtml
}
④注意!要把包的文件夹加入node_modules文件夹中才能正常使用!
使用
const gshtml = require('gshtml');
const str = '<h1 title="abc">hello smoky</h1>';
const strnew = gshtml.gshtml(str);//对html格式进行转义
console.log(strnew);
终端输出:
PS D:\vscode\workspace\nodejs> node .\excTest.js
<h1 title="abc">hello smoky</h1>
express
创建web服务器
const express = require('express');
const app = express();
app.listen('81',function(){
console.log("express服务启动……");
})
和http创建服务器的区别:
http | express | |
---|---|---|
引入 | const http = require(‘http’); | const express = require(‘express’); |
创建服务 | const server = http.createServer(); | const app = express(); |
监听get和post请求
app.get("请求url",(req,res)=>{})
app.get('/user',(req,res)=>{
res.send(
{
name:"zs",gender:"m"
}
);
})
app.post('/user',(req,res)=>{
res.send("post请求成功");
})
url传参
通过req.query.参数名
app.get('/',(req,res)=>{
res.send(
{
name:req.query.name,gender:req.query.gender
}
);
})
动态参数(客户端不写明参数的名字,在服务器进行匹配)
app.get('/user/:name',(req,res)=>{
res.send(req.params)//注意是params不是query哦!
})
动态参数可以有多个
提供静态资源
app.use(express.static('./images'))
images这个路径不会出现在访问路径中,会被跳过。
如果不想忽略:
app.use('/images',express.static('./images'))
第一个参数中的内容可以随意替换,为路径加不同的前缀。
express路由
express路由由请求类型、URL地址、处理函数组成。
app.method(URL,HANDLER)
模块化路由
通过express.Router()
导入模块
const api = require('api');
app.use(['/api',]api)
中间件
和路由的区别是在callback函数中,参数除了req和res,还有next,并且函数体中会有next();
const mw = function(req,res,next){
console.log("我是一个中间件");
next();
}
app.use(mw);//让中间件全局生效
也可以把函数直接写到app.use里面。
局部生效的中间件
在中间件需要生效的路由中,添加函数
const mw1 = function(req,res,next){
console.log("我是一个中间件");
next();
}
app.get('/',mw1,()=>{})//mw1生效
app.get('/user',()=>{})//mw1不生效
中间件
应用级别中间件 通过app.use/get/post绑定到app实例上
路由级别中间件 通过router.use绑定到router实例上
错误级别中间件 包含四个参数(err,req,res,next),错误中间件要定义在所有路由之后(才能捕获错误,防止程序崩溃)。
express内置中间件 (1)express.static 托管静态资源 (2)express.json 解析json格式数据 (3)express.urlencoded 解析URL-encoded格式数据
使用:app.use(epress.json())
app.use(epress.urlencoded({extended:false}))
第三方中间件
数据库连接
查询数据
db.query('select * from users',(err,result)=>{
if(err) return console.log(err.message);
console.log(result);
})
插入数据