文章目录
node.js是什么?
- Node.js是JavaScript 运行时环境
- 通俗易懂的讲,Node.js是JavaScript的运行平台
- Node.js既不是语言,也不是框架,它是一个平台
- 浏览器中的JavaScript
- EcmaScript
- 基本语法
- if
- var
- function
- Object
- Array
- Bom
- Dom
- EcmaScript
- Node.js中的JavaScript
- 没有Bom,Dom
- EcmaScript
- 在Node中这个JavaScript执行环境为JavaScript提供了一些服务器级别的API
- 例如文件的读写
- 网络服务的构建
- 网络通信
- http服务器
- 构建于Chrome的V8引擎之上
- 代码只是具有特定格式的字符串
- 引擎可以认识它,帮你解析和执行
- Google Chrome的V8引擎是目前公认的解析执行JavaScript代码最快的
- Node.js的作者把Google Chrome中的V8引擎移植出来,开发了一个独立的JavaScript运行时环境
- Node.js uses an event-driven,non-blocking I/O mode that makes it lightweight and efficent.
- event-driven 事件驱动
- non-blocking I/O mode 非阻塞I/O模型(异步)
- lightweight and efficent. 轻量和高效
- Node.js package ecosystem,npm,is the larget scosystem of open sourcr libraries in the world
- npm 是世界上最大的开源生态系统
- 绝大多数JavaScript相关的包都存放在npm上,这样做的目的是为了让开发人员更方便的去下载使用
- npm install jquery
node.js第一个程序
//01.js
console.info('hello node');
运行(前提是成功安装node):
在文件目录下打开cmd,输入node+‘文件名’
魔术变量(__dirname)
__dirname:当前文件目录名称
path.join:把两个路径连接起来
const fs = require("fs");
const path = require("path");
console.log(path.join(__dirname,'./demo1.js'));
读取文件(readFile异步)
// 引入核心模块fs
const fs = require("fs");
// 读取文件
fs.readFile("1.js",(err,data)=>{
// 读取文件失败,抛出异常
if(err) throw err;
// 打印读取到的数据(buffer数据)
console.log(data);
// 把数据转换成utf-8编码格式
console.log(data.toString());
})
运行结果:
打印了一个buffer数据和一个我们能看懂的正常文件内容
读取文件(readFileSync同步)
const fs = require("fs");
try {
let data = fs.readFileSync("./1.js","utf-8");
// 打印读取到的数据
console.log(data);
} catch (error) {
// 打印错误信息
console.log(error);
}
console.log("读取文件1");
// 同步(读取没完成,后续代码不执行)
let data1 = fs.readFileSync("./1.js","utf-8");
console.log(data1);
console.log("读取文件2");
打印结果:
本来读取文件是个异步操作,但通过同步函数readFileSync,程序变成了顺序执行。
读取文件(promisify)
注意:
await 不能单独使用,async可以,await必须配合async
await等待 后续的代码一定需要等待前面的代码执行完才会执行,但是底层是异步的
const fs = require("fs");
const path = require("path");
const util = require("util");
// 用promise写法
const readFile = util.promisify(fs.readFile);
let run = async ()=>{
let res1 = await readFile('./2.txt',"utf-8");
console.log(res1);
}
run();
创建一个简单的服务器(http)
const http = require("http"); //创建服务器的方法
const server = http.createServer((req,res)=>{
// 设置通过http访问服务器数据时,浏览器展示的字符编码格式
res.setHeader("content-type","text/html;charset=utf-8");
// req.url请求路径
if(req.url=='/news'){
var data = {status:200,list:[{name:'zs'},{name:'lisi'},{name:'zy'}]};
res.end(JSON.stringify);
}else {
res.write("hello node");
res.end("我是服务器请求后返回的结束方法");//服务器结束必须调用end方法
}
})
.listen(3000,()=>{// 服务器监听端口号为3000
console.log("监听3000端口启动了");
})
express框架
当前目录cmd下安装express:npm install express --save-dev
安装完成后,会生成一个node_modules目录,一个package.json文件,若删除了node_modules目录,通过npm i
即可下载回来 。
使用express有如下四步:
// 学会使用express()和中间件
// 1.引入express
const express = require('express');
// 2.调用express方法
const app = express();
// 中间件
var flag = true;
app.use((req,res,next)=>{
if(!flag){
res.send('err')
}else {
next('hello')
}
})
// 3.处理请求
app.get('/index',(req,res)=>{
res.send("I'm index");
})
// 4.监听端口
app.listen(3000,()=>{
console.log('3000端口开始监听...');
})
module.exports
//01.js
module.exports = middleWare;
//02.js
let middleWare = require("./01.js");
路由(route)
//demo/index.js
const express = require('express');
const indexRoute = express.Router();
indexRoute.get('/index',(req,res)=>{
res.send('/index html')
})
module.exports= indexRoute;
//02.js
// express+route
const express = require('express');
const app = express();
const indexRoute = require('./demo/index');
app.use('/public',indexRoute);
app.listen(3000,(req,res)=>{
console.log('3000 端口开始监听...');
})
mongoose数据库
// 1.引入mongoose
const mongoose = require('mongoose');
// 2.连接
mongoose.connect("mongodb://localhost/playground",{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(res=>{
console.log("数据库连接成功")
})
.catch(err=>{
console.log("数据库连接失败")
})
// 3.创建集合规则
const collectCourse = new mongoose.Schema({
name:String,
age:Number,
hobbies:[String],
isFlage:Boolean,
date:{type:Date,default:Date.now}
})
// 4.用集合规则建表
const myMongoose = mongoose.model('table2',collectCourse);
// 5.向表里添加数据
myMongoose.create({
name:"周阳",
age:21,
hobbies:['sing','dance','rap']
}).then(res=>{
console.log(res)
})
mongoose(查询数据find)
// 查询数据
myMongoose.find().then((res)=>{
console.log(res)
})
// 1.查询所有数据
// mymanggo.find().then((res)=>{
// console.log(res)
// })
// 只查询一条数据
// mymanggo.findOne({name:'zy'}).then((res)=>{
// console.log(res)
// })
// 2.只查三条数据
// mymanggo.find().limit(3).then((res)=>{
// console.log(res);
// })
// 3.查找数据库里所有信息并按年龄升序打印出来
// mymanggo.find().sort({age:1}).then((res)=>{
// console.log(res);
// })
// 升序查询
// mymanggo.find().sort('age').then((res)=>{
// console.log(res);
// })
// 4.查找数据库里所有信息并按年龄降序打印出来
// mymanggo.find().sort({age:-1}).then((res)=>{
// console.log(res);
// })
//排序查询 降序
// mymanggo.find().sort('-age').then(res=>{
// console.log(res)
// })
// 5.查找所有name为zy的人,仅限查10条
// mymanggo.find({name:'zy'}).limit(10).then((res)=>{
// console.log(res)
// })
// 6.组合查询,只展示name age 两列结果
mymanggo.find().select('-_id,nam,age').then((res)=>{
console.log(res)
})
// mymanggo.find().exec((err,data)=>{
// console.log(data)
// })
// 范围查询:年龄大于50 小于100
// mymanggo.find({age:{$lt:100,$gt:30}}).then((res)=>{
// console.log(res)
// })
// 范围查询
// 查询爱好包含“看书”的人
// mymanggo.find({hobbies:{$in:['看书']}}).then(res=>{
// console.log(res)
// })
// 升序排列 前面2条跳过 限制3条
// mymanggo.find().sort({age:1}).skip(2).limit(3).then(res=>{
// console.log(res)
// })
mongoose(修改数据update)
// 修改
mymanggo.updateOne({name:'zy'},{name:'小周'}).then((res)=>{
console.log(res)
});
// 修改所有人的名字为zy
// mymanggo.updateMany({},{name:'zy'}).then((res)=>{
// console.log(res)
// })
mongoose(删除数据delete)
// 删除单个
// mymanggo.findOneAndDelete({}).then(res=>{
// console.log(res)
// })
// 删除多个
mymanggo.deleteMany({}).then(res=>{
console.log(res)
})
Mongoose验证
Mongoose验证:
在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。
常见的验证规则:
required: true 必传字段
minlength:3 字符串最小长度
maxlength: 20 字符串最大长度
min: 2 数值最小为2
max: 100 数值最大为100
enum: [‘html’, ‘css’, ‘javascript’, ‘node.js’]
trim: true 去除字符串两边的空格
validate: 自定义验证器
default: 默认值
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(()=>{
console.log('数据库连接成功');
})
.catch(err=>{
console.log(err,'数据库连接失败')
})
// 创建集合规则(原始)
// const collectCourse = new mongoose.Schema({
// name:String,
// age:Number,
// author:String,
// hobbies:[String],
// isFlag:Boolean,
// date:{type:Date,default:Date.now}
// })
// 创建集合规则(现在)
const collectCourse = new mongoose.Schema({
name:{
type:String,
minlength:2,
maxlength:10,
message:'name 传入的值不符合验证规则'
},
age:{
type:Number,
max:100,
min:0,
required:true,
message:'age 传入的值不符合验证规则'
},
category:{
type:String,
enum:['html','javascript','node.js','php'],
message:'分类名称要在一定的范围内才可以'
},
hobbies:{
type:Array
},
isFlag:Boolean,
date:{type:Date,default:Date.now},
author:{
type:String,
validate:{
// validator自定义校验规则函数
validator:v=>{
return v && v.length>4
},
// 自定义错误信息
message:'author 传入的值不符合验证规则'
}
}
})
// 使用集合规则建表
const self_schema = mongoose.model('self_schema',collectCourse);
// 添加表数据
self_schema.create({
name:"蔡蔡",
age:21
})
.then(res=>{
// 返回创建的那个数据
console.log(res)
})
.catch(err=>{
for(key in err.errors){
console.log(err.errors[key].message)
}
})
// 错误提示:
// Error: self_schema validation failed: age: Path `age` is required.,
// name: Path `name` (`蔡`) is shorter than the minimum allowed length (2).