当前位置:网站首页>node学习
node学习
2022-07-25 15:00:00 【Henry_楠】
全局模块
process.env 环境变量
process.argv 命令行变量
例如:
//命令行输入
node index 11 22
//index.js
console.log(process.argv) //['.../node.exe'(node文件目录),'.../index'(当前文件目录),11,22]
console.log(parseInt(process.argv[2])+parseInt(process.argv[3])) //33
__dirname 当前的目录
系统模块
需要require(),但不需要下载
path:用于处理文件路径和目录路径的使用工具
let path = require('path')
console.log(path.dirname('/node/a/b/1.jpg')) // 目录路径(/node/a/b/)
console.log(path.basename('/node/a/b/1.jpg')) // 文件(1.jpg)
console.log(path.extname('/node/a/b/1.jpg')) // 文件扩展名(.jpg)
核心应用:
//index.js
let path = require('path')
console.log(path.resolve('/node/a/b','../../','c')) // node\c
console.log(path.resolve(__dirname,'index.js')) // 获取到文件的绝对路径,避免用相对路径出错
fs:用于文件的读写操作
读:
//a.txt
abc
//index.js
let fs = require('fs')
fs.readFile('a.txt',(err,data)=>{
if(err){
console.log(err)
}else{
console.log(data) //<Buffer 61 62 63>
console.log(data.toString()) //abc
}
})
//同步写法
let data2 = fs.readFireSync('a.txt')
console.log(data2)
写:
//index.js
let fs = require('fs')
//覆盖写
fs.writeFile('b.txt','月薪2000元',(err)=>{
if(err){
throw err
}else{
console.log('写入成功')
}
})
//追加写
fs.writeFile('b.txt','月薪4000元',{
flag:'a'},(err)=>{
if(err){
throw err
}else{
console.log('写入成功')
}
})
//同步写法
fs.writeFileSync('b.txt','月薪4000元')
自定义模块
require
- 如果有路径就去路径里面找
- 没有的话就去node_modules里面找
- 最后再去node的安装目录里面找
exports:导出
module:批量
//mod.js
//exports.a = 'a'
//exports.b = 'b'
//上面的导出等于下面的导出
module.exports = {
a:'a',
b:'b'
}
//index.js
const mod = require('./mod.js')
console.log(mod.a)//'a'
console.log(mod.b)//'b'
重点:HTTP 模块
//index.js
let http = require('http')
let fs = require('fs')
http.createServer((req,res)=>{
console.log('req',req)
fs.readFile(`./${
req.url}`,(err,data)=>{
if(err){
res.writeHead(404)
res.end('404 not found')
}else{
res.writeHead(200)
res.end(data)
}
})
}).listen(8888)
GET 请求
//index.js
let http = require('http')
let url = require('url')
http.createServer((req,res)=>{
console.log('req.url',req.url)
//url.parse 第一个参数是请求路径 第二个参数是是否要处理query,不处理则是拼接的字符串
let {
pathname,query} = url.parse(req.url,true)
console.log(pathname,query)
}).listen(8888)
<!-- form.html -->
<form action="http://localhost:8888/login">
用户名: <input type="text" name="username">
<br>
密码:<input type="password" name="password">
<br>
<input type="submit" value="提交">
</form>
- url?user=xxx&pass=xxx
- <32K
- url模块
- url.parse(req.url,true)
POST 请求
//index.js
let http = require('http')
let querystring = require('querystring')
http.createServer((req, res) => {
let result = []
req.on('data', buffer => {
result.push(buffer)
})
req.on('end', () => {
let data = Buffer.concat(result).toString() //因为是接收字符串,所以可以直接tostring
console.log(querystring.parse(data))
})
res.end('success')
}).listen(8888)
<!-- form.html -->
<form action="http://localhost:8888/login" method="POST">
用户名: <input type="text" name="username">
<br>
密码:<input type="password" name="password">
<br>
<input type="submit" value="提交">
</form>
- 数据一般放在body请求体里,数据比较大,所以是一段一段接收的
- < 2G
- querystring
- querystring.parse(data)
综合实例
目录结构如下图:
//index.js
let http = require('http')
let fs = require('fs')
let url = require('url')
let querystring = require('querystring')
const users = {
'admin': '123456'
}
http.createServer((req, res) => {
let path, postQuery, getQuery;
if (req.method === 'GET') {
let {
pathname, query } = url.parse(req.url, true)
path = pathname
getQuery = query
cb()
} else if (req.method === 'POST') {
path = req.url
let result = []
req.on('data', buffer => {
result.push(buffer)
})
req.on('end', () => {
postQuery = querystring.parse(Buffer.concat(result).toString())
cb()
})
}
function cb() {
if (path === '/login') {
res.writeHead(200, {
'Content-Type': 'text/plain;charset=utf-8'
})
let {
username, password } = getQuery
if (!users[username]) {
console.log('用户不存在')
res.end(JSON.stringify({
code: 401,
msg: '用户不存在'
}))
} else if (users[username] != password) {
res.end(JSON.stringify({
code: 401,
msg: '密码不正确'
}))
} else {
res.end(JSON.stringify({
code: 0,
msg: '登录成功'
}))
}
} else if (path === '/reg') {
res.writeHead(200, {
'Content-Type': 'text/plain;charset=utf-8'
})
let {
username, password } = postQuery
if (users[username]) {
res.end(JSON.stringify({
code: 401,
msg: '用户已存在'
}))
} else {
users[username] = password
res.end(JSON.stringify({
code: 0,
msg: '注册成功'
}))
}
} else {
fs.readFile(`www${
path}`, (err, data) => {
if (err) {
res.writeHead(404)
res.end('404')
} else {
res.end(data)
}
})
}
}
}).listen(8080)
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="jquery.min.js"></script>
</head>
<body>
用户名: <input type="text" id="username">
<br>
密码:<input type="password" id="password">
<br>
<button id="login">提交</button>
<br>
<button id="reg">注册</button>
<script > (function(){
$('#login').click(function(){
console.log('login click') $.ajax({
url:'/login', method:'get', dataType:'json', data:{
username:$('#username').val(), password:$('#password').val() }, success(res){
if(res.code!==0){
alert(res.msg) }else{
alert('登录成功') location.href="index.html" } } }) }) $('#reg').click(function(){
console.log('reg click') $.ajax({
url:'/reg', dataType:'json', method:'post', data:{
username:$('#username').val(), password:$('#password').val() }, success(res){
if(res.code!==0){
alert(res.msg) }else{
alert('注册成功') } } }) }) })() </script>
</body>
</html>
总结
作用:
- 写webApi
- 中间层
- 前端工程化的一些(webpack、gulp)
深入:koa2/express、MongoDB/mysql 等
进阶
nodemon模块 热更新,采用nodemon替代node执行命令,通过增加nodemon.json的watch增加监听的文件
DEBUG=*
边栏推荐
- The solution to the problem that the progress bar of ros2 installation connext RMW is stuck at 13%
- Niuke multi school E G J L
- [C题目]力扣876. 链表的中间结点
- Process control (Part 1)
- 没错,请求DNS服务器还可以使用UDP协议
- Deployment and simple use of PostgreSQL learning
- SQL优化的一些建议,希望可以帮到和我一样被SQL折磨的你
- LeetCode_因式分解_简单_263.丑数
- 阿里云技术专家邓青琳:云上跨可用区容灾和异地多活最佳实践
- 关于RDBMS和非RDBMS【数据库系统】
猜你喜欢

微信公众号正式环境上线部署,第三方公众平台接入

Nacos2.1.0 cluster construction

51 single chip microcomputer learning notes (1)

06. Neural network like

"Ask every day" briefly talk about JMM / talk about your understanding of JMM

43 box model

冈萨雷斯 数字图像处理 第一章绪论
![[Nacos] what does nacosclient do during service registration](/img/76/3c2e8f9ba19e36d9581f34fda65923.png)
[Nacos] what does nacosclient do during service registration

SSH服务器拒绝了密码

L1和L2正则化
随机推荐
解决asp.net上传文件时文件太大导致的错误
Awk from getting started to digging in (20) awk parsing command line parameters
云安全技术发展综述
sql to linq 之存储过程偏
Thymeleaf notes
LeetCode-198-打家劫舍
安装EntityFramework方法
String type time comparison method with error string.compareto
Deng Qinglin, a technical expert of Alibaba cloud: Best Practices for disaster recovery and remote multi activity across availability zones on cloud
EDA chip design solution based on AMD epyc server
PHP 通过原生CURL实现非阻塞(并发)请求模式
IP地址分类,判断一个网段是子网超网
39 simple version of millet sidebar exercise
41 图片背景综合-五彩导航图
冈萨雷斯 数字图像处理 第一章绪论
直播课堂系统05-后台管理系统
Share a department design method that avoids recursion
I2C device driver hierarchy
[MySQL must know and know] trigger | permission management
[C topic] Li Kou 206. reverse the linked list