当前位置:网站首页>Get to know nodejs for the first time (with cases)
Get to know nodejs for the first time (with cases)
2022-07-28 19:22:00 【Kaka bear】
Catalog
3、 ... and 、Node.js built-in API
One 、 What is? Node.js
It's not a language , library , frame , It is js Runtime environment .nodejs Can parse and execute js Code , Compared with before, only the browser can parse and execute js Code , current Js It can run completely off the browser .Nodejs The author put Chrome Medium V8 The engine was transplanted , Developed an independent js Runtime environment (Nodejs).
Node.js Cannot call DOM and BOM Browser built in API.
Two 、Node.js What can be done
Node.js As a JavaScript Operating environment , It only provides some basic functions and API, However, combining some frameworks and third-party libraries can complete many rich applications .
be based on Express frame (http://www.expressjs.com.cn/), You can quickly build Web application
be based on Electron frame (https://electronjs.org/), Can build cross platform desktop applications
be based on restify frame (http://restify.com/), You can quickly build API Interface project
Read, write and operate the database 、 Create practical command line tools to assist front-end development 、etc…
Node.js What to learn ?
Node.js built-in API modular (fs、path、http etc. ) and The third party API modular (express、mysql etc. )
3、 ... and 、Node.js built-in API
3.1、fs modular
fs The module is Node.js Official 、 A module used to manipulate files . It provides a series of methods and properties , It is used to meet the user's operation requirements for files . for example :
- fs.readFile( path,[options,] callback) Method , Used to read the contents of the specified file ;
Parameters 1: Mandatory Parameters , character string , Represents the path to the file .
Parameters 2: Optional parameters , Indicates the encoding format used to read the file .
Parameters 3: Mandatory Parameters , After reading the file , Get the read result through the callback function .Callback function (err,dataStr): success , err The value is equal to the null; Failure ,err Is a wrong object ,dataStr The value of is undefined
- fs.writeFile(file,data,[options,] callback) Method , Used to write content to the specified file ;
Parameters 1: Mandatory Parameters , A string that needs to specify a file path , Indicates the storage path of the file .
Parameters 2: Mandatory Parameters , Indicates what to write .
Parameters 3: Optional parameters , Indicates the format in which the file contents are written , The default value is utf8.
Parameters 4: Mandatory Parameters , Callback function after file writing .Callback function (err): success , be err The value is equal to the null; Failure , be err The value of is equal to a Error object
// Import built-in modules
const fs = require('fs')
// Reading documents
fs.readFile('./path',function(err,dataStr){
if(err) {
return console.log(' File read failed '+ err.message)
}
console.log(dataStr)
})
// Writing documents
fs.writeFile('./path','String',function(err){
if(err){
return console.log(' File write failed !' + err.message)
}
console.log(' File written successfully !')
})3.2、path Path module
path The module is Node.js Official 、 The module used to process the path . It provides a series of methods and properties , It is used to meet the processing needs of users for paths . for example :
- path.join() Method , Used to splice multiple path fragments into a complete path string
- path.basename(path [,ext]) Method , Used to extract from the path string , Parse the file name
path <string> Required parameters , A string representing a path
ext <string> Optional parameters , Represents the file extension
return : <string> Represents the last part of the path
- path.extname(path) You can get the extension part of the path
3.3、http modular
http modular , Create a server , External provision web service . step :
- Import http modular
- establish web Server instance
- Bind to the server instance request event , Listen for client requests
- Start the server
const http =require('http')
const server = http.createServer()
// req It's the object of the request , Contains data and properties related to the client
// res It's a response object , It contains data and attributes related to the server
server.on(require,(req,res)=>{
// req.url Is requested by the client URL Address ,req.method Is requested by the client method type
const url = req.url
const method = req.method
const str = `Your request url is ${url}, and request method is ${method}`
// call res.setHeader() Method , Set up Content-Type Response head , Solve the problem of Chinese code disorder
res.setHeader('Content-Type', 'text/html; charset=utf-8')
// call res.end() Method , Respond to the client with something
res.end(str)
})
server.listen(80,()=>{
console.log('server running at http://127.0.0.1')
})Four 、 Local service cases
Require access :127.0.0.1 or 127.0.0.1/clock.html It's the clock ; visit : 127.0.0.1/g2048.html yes 2048 Little games ; Visit others 404


Realization principle : utilize http The module listens to the address requested by the front-end customer , According to the address, send the corresponding file , adopt file The module reads and returns to the customer .
Case composition :

among index.js
// Import corresponding modules
const http = require('http')
const fs = require('fs')
const path =require('path')
const server =http.createServer()
server.on('request',function(req,res){
const url = req.url
console.log(url);
if(url==='/'||url==='/clock.html'){
// When accessing '/' or '/clock.html' when , The address read is the same
const fpath = path.join(__dirname,'./clock.html')
fs.readFile(fpath, 'utf8', (err,dataStr)=>{
if(err) {
// If you return Chinese, you need to add a response header , Otherwise, there will be confusion
res.setHeader('Content-Type', 'text/html; charset=utf-8')
return res.end(' File read error ')
}
res.end(dataStr)
})
}else if(url==='/g2048.html' || url==='/c2048.css'||url==='/j2048.js'){
// When html Other documents are linked in the document , Such as css,js when , The browser will actively request resources from the server
// Type in the browser /g2048.html visit 2048 When the page is , Actually visited /g2048.html,/c2048.css ,/j2048.js Three files
// Be careful path The difference between address splicing
const fpath = path.join(__dirname,'js2048',url)
fs.readFile(fpath,'utf8',(err,dataStr)=>{
if(err) {
res.setHeader('Content-Type', 'text/html; charset=utf-8')
return res.end(' File read error ')
}
res.end(dataStr)
})
}else{
// There is no need to add a response header in English
res.end('404 Not Found.')
}
})
server.listen(80,function(){
console.log('server listen at http://127.0.0.1');
})clock.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>
</head>
<body>
<div id="clock">
<p id="date" class="date"></p>
<p id="time" class="time"></p>
<div id="text"> Built-in module [fs path http] Use </div>
</div>
</body>
<script>
const week = [' Sunday ',' Monday ',' Tuesday ',' Wednesday ',' Thursday ',' 5、 ... and ',' Saturday '];
// const cd=new Date();
let timeID = setInterval(updateTime,1000)
updateTime();
function updateTime(){
var cd=new Date();
console.log(cd);
document.getElementById('time').innerHTML=zeroPadding(cd.getHours(),2) + ":" +zeroPadding(cd.getMinutes(),2)+':'+zeroPadding(cd.getSeconds(),2);
document.getElementById('date').innerHTML=zeroPadding(cd.getFullYear(),4) + "-" +zeroPadding(cd.getMonth()+1,2)+'-'+zeroPadding(cd.getDate(),2)+' '+week[cd.getDay()];
}
function zeroPadding(num,digit){
let zero='';
for (let i=0;i<digit;i++){
zero+='0'
};
return (zero+num).slice(-digit);
}
</script>
<style>
html,body{
height: 100%;
margin:0;
padding: 0;
box-sizing: border-box;
}
body{
background: #0f3854;
background: radial-gradient(ellipse at center,#0a2e38 0%,#000000 70%);
background-size: 100%;
}
p {
margin: 0;
padding: 0;
}
#clock {
font-family: 'Share Tech Mono', monospace;
color: #ffffff;
text-align: center;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
color: #daf6ff;
text-shadow: 0 0 20px rgba(10, 175, 230, 1), 0 0 20px rgba(10, 175, 230, 0);
}
#clock .time {
letter-spacing: 0.05em;
font-size: 80px;
padding: 5px 0;
}
#clock .date {
letter-spacing: 0.1em;
font-size: 24px;
}
#clock .text {
letter-spacing: 0.1em;
font-size: 15px;
padding: 20px 0 0;
}
</style>
</html>JavaScript Little games 2048-Javascript Document resources -CSDN download
Recommend a front-end website ( Extranet ):https://codepen.io/
边栏推荐
- 3、 Uni app fixed or direct to a certain page
- 6-20 vulnerability exploitation proftpd test
- VIM learning manual
- 【滤波跟踪】基于EKF、时差和频差定位实现目标跟踪附matlab代码
- Is two months of software testing training reliable?
- Minio distributed file system learning notes
- 关于白盒测试,这些技巧你得游刃有余~
- Overview and working principle of single chip microcomputer crystal oscillator
- uwb模块实现人员精确定位,超宽带脉冲技术方案,实时厘米级定位应用
- Getting started with QT & OpenGL
猜你喜欢

2022年暑假ACM热身练习3(详细)

Learn from Li Mu in depth -softmax return

Pytorch:交叉熵损失(CrossEntropyLoss)以及标签平滑(LabelSmoothing)的实现

Libgdx learning path 01: libgdx introduction and running tutorial

Web 3.0 development learning path

1、 My first wechat applet

Applet applet jump to official account page

Accumulation and development -- the way of commercialization of open source companies

Cv5200 wireless WiFi communication module, wireless video image transmission, real-time wireless communication technology

【物理应用】大气吸收损耗附matlab代码
随机推荐
Application value of MES production management system to equipment
Server body 21: pre compilation processing by different compilers (a brief introduction to MSVC and GCC)
R语言与数据分析实战11-数据的删除
当CNN遇见Transformer《CMT:Convolutional Neural Networks Meet Vision Transformers》
Application of time series database in bridge monitoring field
Nips18(AD) - 利用几何增广的无监督异常检测《Deep Anomaly Detection Using Geometric Transformations》
What if the content of software testing is too simple?
【数据分析】基于MATLAB实现SVDD决策边界可视化
Pytest custom hook function
RFs self study notes (II): theoretical measurement model - without clutter but with detection probability
QT widget promoted to QWidget
SRS4.0安装步骤
Is the software testing industry really saturated?
From Bayesian filter to Kalman filter (2)
1、 My first wechat applet
三类6种地图可视化软件测评,最好用的工具居然是它
The ever-changing pointer ----- C language
【图像隐藏】基于DCT、DWT、LHA、LSB的数字图像信息隐藏系统含各类攻击和性能参数附matlab代码
ACM warm-up exercise 3 in 2022 summer vacation (detailed)
Application of TSDB in civil aircraft industry