当前位置:网站首页>Node learning
Node learning
2022-07-25 15:26:00 【Henry_ Nan】
Global module
process.env environment variable
process.argv Command line variables
for example :
// Command line input
node index 11 22
//index.js
console.log(process.argv) //['.../node.exe'(node File directory ),'.../index'( Current file directory ),11,22]
console.log(parseInt(process.argv[2])+parseInt(process.argv[3])) //33
__dirname Current directory
System module
need require(), But you don't need to download it
path: Tools for handling file paths and directory paths
let path = require('path')
console.log(path.dirname('/node/a/b/1.jpg')) // Directory path (/node/a/b/)
console.log(path.basename('/node/a/b/1.jpg')) // file (1.jpg)
console.log(path.extname('/node/a/b/1.jpg')) // File extension (.jpg)
Core applications :
//index.js
let path = require('path')
console.log(path.resolve('/node/a/b','../../','c')) // node\c
console.log(path.resolve(__dirname,'index.js')) // Get the absolute path to the file , Avoid making mistakes with relative paths
fs: Used for reading and writing files
read :
//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
}
})
// Synchronous writing
let data2 = fs.readFireSync('a.txt')
console.log(data2)
Write :
//index.js
let fs = require('fs')
// Overwrite
fs.writeFile('b.txt',' a monthly salary 2000 element ',(err)=>{
if(err){
throw err
}else{
console.log(' Write successfully ')
}
})
// Additional writing
fs.writeFile('b.txt',' a monthly salary 4000 element ',{
flag:'a'},(err)=>{
if(err){
throw err
}else{
console.log(' Write successfully ')
}
})
// Synchronous writing
fs.writeFileSync('b.txt',' a monthly salary 4000 element ')
Custom module
require
- If there is a path, go to the path to find
- If not, go node_modules Inside looking for
- Finally, go to node In the installation directory of
exports: export
module: Batch
//mod.js
//exports.a = 'a'
//exports.b = 'b'
// The above export is equal to the following export
module.exports = {
a:'a',
b:'b'
}
//index.js
const mod = require('./mod.js')
console.log(mod.a)//'a'
console.log(mod.b)//'b'
a key :HTTP modular
//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 request
//index.js
let http = require('http')
let url = require('url')
http.createServer((req,res)=>{
console.log('req.url',req.url)
//url.parse The first parameter is the request path The second parameter is whether to process query, If it is not processed, it is a spliced string
let {
pathname,query} = url.parse(req.url,true)
console.log(pathname,query)
}).listen(8888)
<!-- form.html -->
<form action="http://localhost:8888/login">
user name : <input type="text" name="username">
<br>
password :<input type="password" name="password">
<br>
<input type="submit" value=" Submit ">
</form>
- url?user=xxx&pass=xxx
- <32K
- url modular
- url.parse(req.url,true)
POST request
//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() // Because it is the receiving string , So you can directly tostring
console.log(querystring.parse(data))
})
res.end('success')
}).listen(8888)
<!-- form.html -->
<form action="http://localhost:8888/login" method="POST">
user name : <input type="text" name="username">
<br>
password :<input type="password" name="password">
<br>
<input type="submit" value=" Submit ">
</form>
- The data is usually placed in body In the body of the request , Big data , So it's received segment by segment
- < 2G
- querystring
- querystring.parse(data)
Comprehensive example
The directory structure is shown in the figure below :
//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(' The user doesn't exist ')
res.end(JSON.stringify({
code: 401,
msg: ' The user doesn't exist '
}))
} else if (users[username] != password) {
res.end(JSON.stringify({
code: 401,
msg: ' Incorrect password '
}))
} else {
res.end(JSON.stringify({
code: 0,
msg: ' Login successful '
}))
}
} 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: ' The user already exists '
}))
} else {
users[username] = password
res.end(JSON.stringify({
code: 0,
msg: ' Registered successfully '
}))
}
} 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>
user name : <input type="text" id="username">
<br>
password :<input type="password" id="password">
<br>
<button id="login"> Submit </button>
<br>
<button id="reg"> register </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(' Login successful ') 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(' Registered successfully ') } } }) }) })() </script>
</body>
</html>
summary
effect :
- Write webApi
- Middle layer
- Some of the front-end engineering (webpack、gulp)
thorough :koa2/express、MongoDB/mysql etc.
Advanced
nodemon modular Hot update , use nodemon replace node Carry out orders , By increasing the nodemon.json Of watch Add listening files
DEBUG=*
边栏推荐
- pageHelper不生效,sql没有自动加上limit
- ML - 语音 - 语音处理介绍
- MATLAB 如何生产随机复序列
- Distributed principle - what is a distributed system
- 用OpenPose进行单个或多个人体姿态估计
- matlab--CVX优化工具包安装
- Spark memory management mechanism new version
- How to finally generate a file from saveastextfile in spark
- Ml speech depth neural network model
- 伤透脑筋的CPU 上下文切换
猜你喜欢
随机推荐
谷歌云盘如何关联Google Colab
How to solve the problem of scanf compilation error in Visual Studio
redis淘汰策列
图论及概念
Example of password strength verification
Spark AQE
Endnote 添加中文GBT7714样式 word中如何引用文献
Scala111-map、flatten、flatMap
为什么PrepareStatement性能更好更安全?
mysql heap表_MySQL内存表heap使用总结-九五小庞
Promise对象与宏任务、微任务
JVM-垃圾收集器详解
记一次Yarn Required executor memeory is above the max threshold(8192MB) of this cluster!
记一次Spark报错:Failed to allocate a page (67108864 bytes), try again.
The implementation process of inheritance and the difference between Es5 and ES6 implementation
你准备好脱离“内卷化怪圈”了吗?
反射-笔记
CGO is realy Cool!
CGO is realy Cool!
Spark提交参数--files的使用







