简介
- node 开启repl环境,用于测试
C:\Users\一>node
Welcome to Node.js v16.18.0.
1 + 1
2
function add(a,b){
… return a+b;}
undefined
add
[Function: add]node name.js//执行js文件
node-modules模块
- npm包管理工具
npm init :建立模块
npm publish:发布
npm install 模块名 --save;下载包在node_modules目录
npm uninstall 模块名
-g:全局
npm list -g:查看所有全局安装的模块
C:\Users\一>npm list -g
E:\ProgramFiles(x86)\node.js\node_global
+-- @vue/cli-init@5.0.8
+-- @vue/cli@5.0.8
+-- cnpm@8.4.0
+-- express@4.18.1
+-- install@0.13.0
+-- nodemon@2.0.20
package.json:包的属性,名字和版本,dependencies-依赖包列表
模块
- required引入模块
var/const name = require("模块名")//自带
var/const name = require(path: '路径')//自建
-
export对象是公开模块的接口,每个js文件相当于一个模块
-
暴露数据
①module.exports = {
对象名:值};
②module.exports.属性 = 值;
③function Name(){}
module.expoerts = Name
-
导入调用模块
var Hello = require('./hello'); // ./是当前目录 hello = new Hello();
对象名:值
};
②module.exports.属性 = 值;
③function Name(){}
module.expoerts = Name
fs
- 写入
方法 | 说明 |
---|---|
writeFile | 异步写入 |
writeFileSync | 同步写入 |
appendFile / appendFileSync | 追加写入 |
createWriteStream | 流式写入 |
fs.writeFile(file, data[, options], callback)
fs.writeFileSync(file, data[, options])
同步处理 JavaScript 主线程 会等待 其他线程的执行结果,然后再继续执行主线程的代码,效率较低
异步处理 JavaScript 主线程 不会等待 其他线程的执行结果,直接执行后续的主线程代码,效率较好
流式写入,适合多次何大文件
let ws = fs.createWriteStream('./观书有感.txt');
ws.write('天光云影共徘徊\r\n');
ws.write('问渠那得清如许\r\n');
ws.write('为有源头活水来\r\n');
ws.end();
ws.write('半亩方塘一鉴开\r\n');
- 读取文件
方法 | 说明 |
---|---|
readFile | 异步读取 |
readFileSync | 同步读取 |
createReadStream | 流式读取 |
fs.readFile(file[, options], callback(error, data))
const fs = require('fs');
fs.readFile('hello.txt', 'utf8', (err, data) => {
if (err) {
// 失败
console.log(err)
} else {
// 成功
console.log('异步读取数据:' + data2)
}
});
fs.readFileSync(file[, options])
const fs = require('fs');
try {
const data = fs.readFileSync('hello.txt', 'utf8');
console.log(data);
} catch(e) {
// 文件不存在,或者权限错误
throw e;
}
- 移动、重命名
fs.rename(oldPath, newPath, callback)
fs.renameSync(oldPath, newPath)
fs.unlink(path, callback)
- 操作
方法 | 说明 |
---|---|
mkdir / mkdirSync | 创建文件夹 |
readdir / readdirSync | 读取文件夹 |
rmdir / rmdirSync | 删除文件夹 |
path
API | 说明 |
---|---|
path.resolve | 拼接规范的绝对路径 常用 |
path.sep | 获取操作系统的路径分隔符 |
path.parse | 解析路径并返回对象 |
path.basename | 获取路径的基础名称 |
path.dirname | 获取路径的目录名 |
path.extname | 获得路径的扩展名 |
const path = require('path');
//获取路径分隔符console.log(path.sep);
//拼接绝对路径
console.log(path.resolve( dirname, 'test'));
//解析路径
let pathname = 'D:/program file/nodejs/node.exe'; console.log(path.parse(pathname));
//获取路径基础名称console.log(path.basename(pathname))
//获取路径的目录名console.log(path.dirname(pathname));
//获取路径的扩展名console.log(path.extname(pathname));
相对路径:相对于当前路径
./座右铭.txt 当前目录下的座右铭.txt
座右铭.txt 等效于上面的写法
…/座右铭.txt 当前目录的上一级目录中的座右铭.txt
__dirname
:这是一个常量,表示:当前执行文件所在完整目录。
fs.readFile(__dirname + '/123.txt','utf-8',(err,data)=>{
if(err){
console.error("失败")
}
console.log(data)
});
let data = fs.readFileSync( __dirname + '/123.txt','utf-8');
console.log(data);
__filename
:这是一个常量。表示:当前执行文件的完整目录 + 文件名。process.cwd
:获取当前执行 Node命令 时的目录名。- path.join() 将多个路径进行拼接:path.join([…paths]);
const path = require('path');
const result1 = path.join(__dirname, './app.js');
console.log(result1); // 返回:/Users/smyhvae/qianguyihao/app.js
path.join('/a', '/b/c', '../', './d', 'e')
// 输出 \a\b\d\e
// 注意:../ 会抵消它之前的一层路径,所以没有成路径c
// 返回一个拼接后的路径字符串
HTTP
请求报文
- 请求行:
- 请求方法:(get、post、put、delete等)
- 请求 URL(统一资源定位器):定位服务器资源
- HTTP协议版本号
//url解析
http://www.baidu.com:80/index.html?a=100&b=200#logo
http 协议(https、ftp、ssh等)
www.baidu.com 域名
80 端口号
/index.html 路径
a=100&b=200 查询字符串
#logo 哈希(锚点链接)
- 请求头
- 键值对:『头名:头值』
请求头 | 解释 |
---|---|
Host | 主机名 |
Connection | 连接的设置 keep-alive(保持连接);close(关闭连接) |
Cache-Control | 缓存控制 max-age = 0 (没有缓存) |
Upgrade- Insecure- Requests | 将网页中的http请求转化为https请求(很少用)老网站升级 |
User-Agent | 用户代理,客户端字符串标识,服务器可以通过这个标识来识别这个请求来自哪个客户端 ,一般在PC端和手机端的区分 |
Accept | 设置浏览器接收的数据类型 |
Accept-Encoding | 设置接收的压缩方式 |
Accept- Language | 设置接收的语言 q=0.7 为喜好系数,满分为1 |
Cookie |
-
请求体
(可以是空)==> GET请求,
(也可以是字符串,还可以是JSON)===> POST请求
例如:
字符串:keywords=手机&price=2000
JSON:{“keywords”:“手机”,“price”:2000}
响应报文
-
响应行
HTTP版本号 响应状态码 响应状态描述
状态码:200 成功;403:禁止请求。。。 -
响应头
- Cache-Control:缓存控制
- private 私有的,只允许客户端缓存数据
- Connection 链接设置
- Content-Type:text/html;charset=utf-8 设置响应体的数据类型以及字符集,响应体为html,字符集utf-8
- Content-Length:响应体的长度,单位为字节
- 空行
- 响应体:类型灵活
搭建服务器
- 浏览器每一次刷新就是在向某端口发出HTTP请求
// 引入node 内置的http 模块
const http = require('http');
// 默认地址
// const hostname = '127.0.0.1';
// 要监听的端口号
const port =8000;
// 1.创建 web 服务器
//2.req:请求报文,可获得请求报文内容
//res:响应报文,可设置内容
//3.函数在接受到服务器(HTTP)请求时执行
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html;charset=utf-8');
console.log(req.url);
res.end('<h1>返回消息</h1>');
});
//服务器监听8000端口,服务启动时执行回调函数
server.listen(port, () => {
console.log(${port});
});
打开localhost 8000显示返回消息
- 注意事项
- 响应内容乱码
response.setHeader('content-type','text/html;charset=utf-8');
- HTTP内容在浏览器网络中查看
- request
- 注意:
- request.url 只能获取路径以及查询字符串,无法获取 URL 中的域名以及协议的内容
- request.headers 将请求信息转化成一个对象,并将属性名都转化成了『小写』
含义 | 语法 |
---|---|
请求方法 | request.method |
请求版本 | request.httpVersion |
请求路径 | request.url |
URL 路径 | require(‘url’).parse(request.url).pathname |
URL 查询字符串 | require(‘url’).parse(request.url, true).query |
请求头 | request.headers |
请求体 | request.on(‘data’, function(chunk){}) request.on(‘end’, function(){}); |
-
response
作****用 语****法 设置响应状态码 response.statusCode 设置响应状态描述 response.statusMessage ( 用的非常少 ) 设置响应头信息 response.setHeader(‘头名’, ‘头值’) 设置响应体 response.write(‘xx’) response.end(‘xxx’)
express
- 服务端框架,express-generator:应用生成器
cnpm i express-generator -g//全局安装
express 项目名称 //建立项目
cnpm i//安装package-json里的依赖
cnpm start //启动项目
//在www配置的端口号中打开:localhost:3000
> express-end@0.0.0 start
> node ./bin/www
-
localhost:3000定位的是public端口
-
应用
-
app.use(express.static('public')) //静态文件 app.use('/static', express.static('public')) 通过 /static 前缀地址来访问 public 目录中的文件
-
-
路由
const express = require('express') //1.应用对象 const app = express(); //2.创建路由:请求方法和路径 app.get('/', (req, res) => { //2.1 express兼顾原生http方法 console.log(req.method); console.log(req.url); console.log(req.httpVersion); console.log(req.headers); //2.2 express 独有的获取报文的方式 //获取查询字符串 console.log(req.query); // 『相对重要』 // 获取指定的请求头,host为其内容之一:localhost:3000 console.log(req.get('host')); res.end('hello express server'); }); //自定义 404 路由 app.all("*", (req, res) => { res.send('<h1>404 Not Found</h1>') }); //3.启动 app.listen(3000, () =>{ console.log('服务已经启动, 端口监听为 3000...'); });
express路由
路由结构:app.method(path, handler);
- app:express实例
- method:是一个HTTP请求方法:get、post、put、delete、all
- path:服务端路径
- handler:当路由匹配到时执行的回调函数。参数:
request
和response
对象分别处理请求和响应数据
API:http://expressjs.jser.us/3x_zh-cn/api.html#req.params
-
request
就是请求对象,response
是响应对象, 通常用 res 和 req 简写代替。req 里面有些比较常用的成员,我也列举出来了。req.body()
: 客户端返回的请求体req.params()
、req.query()
:客户端的请求参数即url中的参数(数据)。 用于拿到前端界面的请求参数去进行处理req.cookies()
:客户端 cookiesResponse.json()
:接受一个对象或数组,并在发送之前将其转换为JSON:res.json({ username: ‘Flavio’ })Response.set()
:改变任何HTTP头值:res.set(‘Content-Type’, ‘text/html’)快捷方式 res.type('.html') // => 'text/html' res.type('html') // => 'text/html' res.type('json') // => 'application/json' res.type('application/json') // => 'application/json' res.type('png') // => image/png:
-
response设置
//获取请求的路由规则 app.get("/response", (req, res) => { //1. express 中设置响应的方式兼容 HTTP 模块的方式 res.statusCode = 404; res.statusMessage = 'xxx'; res.setHeader('abc','xyz'); res.write('响应体'); res.end('xxx'); //2. express 的响应方法 res.status(500); //设置响应状态码 res.set('xxx','yyy');//设置响应头 res.send('中文响应不乱码');//设置响应体 //连贯操作 res.status(404).set('xxx','yyy').send('你好朋友') //3. 其他响应 res.redirect('http://atguigu.com')//重定向 res.download('./package.json');//下载响应 res.json();//响应 JSON res.sendFile(__dirname + '/home.html') //响应文件内容 });
-
中间件函数
//声明函数 let recordMiddleware = function(request,response,next){ //实现功能代码 //执行next函数(当如果希望执行完中间件函数之后,仍然继续执行路由中的回调函数,必须调用next next(); } app.use(函数)//全局 app.get('/路径',`中间件函数1`,`中间件函数2`,(request,response)=>{});//路由
-
body-parser
处理请求体
const bodyParser = require('body-parser'); //获取中间件函数 //处理 querystring 格式的请求体 let urlParser = bodyParser.urlencoded({extended:false})); //处理 JSON 格式的请求体 let jsonParser = bodyParser.json(); //使用中间件函数 app.post('/login', urlParser, (request,response)=>{ //获取请求体数据 console.log(request.body); //用户名 console.log(request.body.username); //密码 console.log(request.body.userpass); response.send('获取请求体数据'); });
-
路由
//homeRouter.js //1. 导入 express const express = require('express'); //2. 创建路由器对象 const router = express.Router(); //3. 在 router 对象身上添加路由 router.get('/', (req, res) => { res.send('首页'); }) router.get('/cart', (req, res) => { res.send('购物车'); }); //4. 暴露 module.exports = router;
//主文件 const express = require('express'); const app = express(); //5.引入子路由文件 const homeRouter = require('./routes/homeRouter'); //6.设置和使用中间件 app.use(homeRouter); app.listen(3000,()=>{ console.log('3000 端口启动 '); })
mysql
http://t.csdn.cn/P5eSu
1.打开数据库
net start mysql 启动服务
quit/exit 退出
- 下载MySQL:npm install mysql
- 配置数据库,连接数据库
// 1. 引入mysql模块
let mysql = require('mysql');
// 2. 创建连接配置
const conn = mysql.createConnection({
host:'localhost',
user:'root',
password:'123456',
database:'demo1',
port:3306//可忽略
})
// 3. 建立连接
conn.connect();
// 4. 准备sql语句
// let sql = 'select * from student'; 查询语句
// let sql = 'insert into student values(null,"冉祎航",20,1,"计算机",2)'
// let sql = 'update student set age = 30 where id = 31'
// let sql = 'delete from student where id = 31'
// 5. 执行sql语句
let sql = 'select * from user'
conn.query(sql,(err,results,fields)=>{
if(err){
return err;
}
console.log(results);
})
// 6. 结束连接;如果不再有sql被执行,一定要关闭连接,否则会一直占用资源
conn.end();
/*
对于增删改查而言,只有查询的语句,返回值是一个数据,包含所有查询结果,每一条记录是一条数据;
其他的返回的都是对象,affectRows表示受影响的行数,一般情况下通过该字段判断增删改的结果
*/