Home > Article > Web Front-end > Get to know Node.js and talk about the modularity of node
This article will introduce you to Node.js, see how to check the version number of the installed Node.js, and talk about the modularization of node. I hope it will be helpful to everyone!
Concept: is a JavaScript running environment based on the Chrome V8 engine. [Recommended learning: "nodejs Tutorial"]
Node.js official website address: https://nodejs.org/zh-cn/
Note:
① The browser is the front-end running environment for JavaScript.
② Node.js is the back-end running environment for JavaScript.
③ Node.js cannot call
built-in browser APIs such as DOM and BOM.
Double-click the official homepage of Node.js (nodejs.org/en/) to download
① LTS is a long-term stable version. For enterprise-level projects that pursue stability, installation is recommended LTS version of Node.js.
② Current is an early adopter version of new features. For users who are keen on trying new features, it is recommended to install the Current version of Node.js. However, there may be hidden bugs or security vulnerabilities in the Current version, so it is not recommended to use the Current version of Node.js in enterprise-level projects.
Check the version number of the installed Node.js) to open the run panel and enter cmd and press Enter directly to open the terminalOpen the terminal and enter the command
node –vin the terminal to view the downloaded version
Shortcut keys in the terminalkey to quickly locate the last executed command ② Use
tabkey can quickly complete the path ③ Use
esckey to quickly clear the currently entered command ④ Enter the
clscommand , you can clear the terminal
Modularitymodules are units that can be combined, decomposed and replaced ##Modularization in the programming field means
abiding by fixed rulesinto multiple small modules that are independent and interdependent to modularize the code Benefits
Built-in modules (built-in modules are provided by , path
, http
, etc.) Custom modules (user-created Each
Third-party modules (modules developed by third parties are not officially provided built-in modules, nor It is not a custom module created by the user.
Use the
fs file system module
fs module is a module officially provided by Node.js for operating files. It provides a series of methods and attributes to meet the user's file operation needs.
1. Syntax format of
fs.readFile()Parameter interpretation:
• Parameter 1: Required Parameter, string, indicating the path of the file.
• Parameter 2: Optional parameter, indicating what encoding format is used to read the file.
• Parameter 3: Required parameter. After the file reading is completed, the reading result is obtained through the callback function.
Example:
// 1. 导入 fs 模块,来操作文件 const fs = require('fs') // 2. 调用 fs.readFile() 方法读取文件 // 参数1:读取文件的存放路径 // 参数2:读取文件时候采用的编码格式,一般默认指定 utf8 // 参数3:回调函数,拿到读取失败和成功的结果 err dataStr fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) { // 2.1 打印失败的结果 // 如果读取成功,则 err 的值为 null // 如果读取失败,则 err 的值为 错误对象,dataStr 的值为 undefined // console.log(err) // console.log('-------') // 2.2 打印成功的结果 console.log(dataStr) // 判断文件是否读取成功 if (err) { return console.log("读取文件失败!" + err.message) } console.log("读取文件成功!" + dataStr) })
2, fs.writeFile The syntax format of ()
Parameter interpretation:
• Parameter 1: Required parameter, you need to specify a String of file path, indicating the storage path of the file.
• Parameter 2: Required parameter, indicating the content to be written.
• Parameter 3: Optional parameter, indicating the format in which to write the file content. The default value is utf8.
• Parameter 4: Required parameter, callback function after file writing is completed.
Example:
// 1. 导入 fs 文件系统模块 const fs = require('fs') // 2. 调用 fs.writeFile() 方法,写入文件的内容 // 参数1:表示文件的存放路径 // 参数2:表示要写入的内容 // 参数3:回调函数 fs.writeFile('./files/3.txt', 'ok123', function(err) { // 2.1 如果文件写入成功,则 err 的值等于 null // 2.2 如果文件写入失败,则 err 的值等于一个 错误对象 console.log(err) // 3判断文件是否写入成功 if (err) { return console.log('文件写入失败!' + err.message) } console.log('文件写入成功!') })
fs module - problem of dynamic path splicing
When using the fs module to operate files, If the provided operation path is a relative path starting with ./ or ../ , it is easy to cause dynamic path splicing errors.
Cause: When the code is running, will dynamically splice the full path of the file being operated on from the directory where the node command is executed.
Solution: When using the fs module to operate files, provide the complete path directly, do not provide a relative path starting with ./ or ../, thereby preventing The problem of dynamic path splicing.
Concept: is officially provided by Node.js and is used to process paths Module
1, path.join() method, is used to splice multiple path fragments into a complete path string
Grammar format
Parameter interpretation:
• ...paths Sequence of path fragments
• Return value:
Code example
##Note:
In the future, all operations involving path splicing will be processed using the path.join() method. Do not use directly to concatenate strings.
2. path.basename() Gets the file name in the path
Parameter interpretation: • path is a required parameter, indicating a path String • ext optional parameter, indicating the file extension • Return: indicating the last part of the pathCode example
3. path.extname() Gets the file extension in the path
Syntax format
Parameter interpretation: • path is a required parameter, a string representing a path• Return: Return the obtained Extension string****Code example
Requirements:
Split the page.html page in the material directory into three files, which are: • index.css• index.js• index.htmlmaterial page.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=."> <title>Document</title> <style> html, body { margin: ; padding: ; height: %; background-image: linear-gradient(to bottom right, red, gold); } .box { width: px; height: px; ">); border-radius: px; position: absolute; left: %; top: %; transform: translate(-%, -%); box-shadow: px px px #fff; text-shadow: px px px white; display: flex; justify-content: space-around; align-items: center; font-size: px; user-select: none; padding: px; /* 盒子投影 */ -webkit-box-reflect: below px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(%, transparent), to(rgba(, , , .))); } </style> </head> <body> <div> <div id="HH"></div> <div>:</div> <div id="mm"></div> <div>:</div> <div id="ss"></div> </div> <script> window.onload = function() { // 定时器,每隔 秒执行 次 setInterval(() => { var dt = new Date() var HH = dt.getHours() var mm = dt.getMinutes() var ss = dt.getSeconds() // 为页面上的元素赋值 document.querySelector("#HH").innerHTML = padZero(HH) document.querySelector("#mm").innerHTML = padZero(mm) document.querySelector("#ss").innerHTML = padZero(ss) }, ) } // 补零函数 function padZero(n) { return n > ? n : "" + n } </script> </body> </html>
The split code is as follows:
// 导入 // 导入fs文件模块 const fs = require("fs") // 导入路径 const path = require("path") // const { join } = require("path/posix") 坑:敲resove这几个字代码后,会自动形成此句代码,导致报错,将其注释或者删除即可正常运行 // 定义正在表达式 // \代表转义符,\s匹配空格(包含换行符、制表符空格符),\S非空格 // []匹配方括号中的任意字符, *重复次或更多次, const regStyle = /<style>[\s\S]*</style>/ const regStcript = /<script>[\s\S]*</script>/ // 读取文件 fs.readFile(path.join(__dirname, "./index.html"), "utf", function (err, data) { // 判断文件是否读取成功 if (err) { // 读取文件失败 console.log("读取文件失败" + err.message) } else { // 读取文件成功 console.log("读取文件成功" + data) // 读取文件成功后,调用对应的 个方法,解析出 css、js、html 内容 resoveCss(data) resoveJs(data) resoveHTML(data) } // 写入html.css样式表 function resoveCss(htmlStr) { // 使用正则提取页面中的 <style></style> const r = regStyle.exec(htmlStr) // cnsole.log(r[]) // 将提取出来的样式字符串,做进一步的处理 const newCss = r[].replace("<style>", "").replace("</style>", "") //###注意: 写入文件时,需要先建个文件(如index.css),然后再终端运行 node .\clock.js,样式表里才会显示出来 fs.writeFile( path.join(__dirname, "./index.css"), newCss, function (err, data) { if (err) { console.log("CSS样式文件写入失败" + err.message) } else { console.log("CSS样式文件写入成功") } } ) } // 写入html.js样式表 function resoveJs(htmlJs) { // exec 检索字符串 中的正在表达式的匹配 const r = regStcript.exec(htmlJs) // r[]拿到匹配成功后索引为的元素 const newJS = r[].replace("<script>", "").replace("</script>", "") fs.writeFile( path.join(__dirname, "./index.js"), newJS, function (err, data) { if (err) { console.log("JS文件写入成功" + err.message) } else { console.log("JS文件写入成功!") } } ) } // 写入index.html样式表 function resoveHTML(html) { const newHTML = html .replace(regStyle, '<link rel="stylesheet" href="./index.css">') .replace(regStcript, '<script src="./index.js"></script>') fs.writeFile(path.join(__dirname, "./index.html"), newHTML, function (err) { if (err) { console.log("HTML文件写入失败!" + err.message) } else { console.log("HTML文件写入成功!") } }) } })
Concept: is used to create web Server module. Through the
http.createServer()
method provided by the http
module, you can easily turn an ordinary computer into a Web Server to provide external
Web resource services
http module to create a
Web server, you need to import it first:
const http = require('http')
http
模块的作用:1、服务器和普通电脑的区别在于,服务器上安装了 web
服务器软件
2、我可可以基于 Node.js
提供的 http
模块,通过几行简单的代码,就能轻松的手写一个服务器软件,从而对外提供 web
服务
ip
地址IP 地址
就是互联网上每台计算机的唯一地址,因此 IP 地址
具有唯一性
IP 地址
的格式:通常用“点分十进制”表示成(a.b.c.d)
的形式,其中,a,b,c,d
都是 0~255 之间的十进制整数
IP
地址(192.168.1.1)
域名和域名服务器
尽管 IP 地址
能够唯一地标记网络上的计算机,但 IP地址
是一长串数字,不直观,而且不便于记忆,于是人们又发明了另一套字符型的地址方案,即所谓的域名地址(Domain Name)
IP地址
和 域名
是一一对应的关系,这份对应关系存放在一种叫做域名服务器 (DNS,Domain name server)
的电脑中。使用者只需通过好记的域名访问对应的服务器即可,对应的转换工作由域名服务器实现。因此,域名服务器就是提供 IP 地址
和域名之间的转换服务的服务器
注意事项:
1. 单纯使用 `IP 地址`,互联网中的电脑也能够正常工作。但是有了域名的加持,能让互联网的世界变得更加方便 2.在开发测试期间, 127.0.0.1 对应的域名是 localhost,它们都代表我们自己的这台电脑,在使用效果上没有任何区别
在一台电脑中,可以运行成百上千个 web 服务
每个web 服务
都对应一个唯一的端口号
客户端发送过来的网络请求,通过端口号,可以被准确地交给对应的 web 服务
进行处理
创建web服务器
实现步骤和核心代码
// 1. 导入 http 模块 const http = require('http') // 2. 创建 web 服务器实例 // 调用 http.createServer() 方法,即可快速创建一个 web 服务器实例 const server = http.createServer() // 3. 为服务器实例绑定 request 事件 // 为服务器实例绑定 request 事件,即可监听客户端发送过来的网络请求 // 使用服务器实例的 .on() 方法,为服务器绑定一个 request 事件 server.on('request', function (req, res) { console.log('Someone visit our web server.') }) // 4.调用服务器实例的 .listen() 方法,即可启动当前的 web 服务器实例 server.listen(8080, function () { console.log('server running at http://127.0.0.1:8080') })
req
请求对象const http = require('http') const server = http.createServer() // req 是请求对象,包含了与客户端相关的数据和属性 server.on('request', (req, res) => { // req.url 是客户端请求的 URL 地址 const url = req.url // req.method 是客户端请求的 method 类型 const method = req.method const str = `Your request url is ${url}, and request method is ${method}` console.log(str) // 调用 res.end() 方法,向客户端响应一些内容 res.end(str) }) server.listen(80, () => { console.log('server running at http://127.0.0.1') })
res
响应对象
在服务器的 request 事件处理程序中,如果想访问与服务器相关的数据和属性,可以使用如下方式
server.on('request', function (req, res) { // res 是响应对象,它包含了与服务器相关的数据和属性 // 例如:将字符串发送到客户端 const str = `${req.url} -- ${req.method}` // res.end() 方法的作用 // 向客户端发送指定的内容,并结束这次请求的处理过程 res.end(str) })
当调用 res.end()
方法,向客户端发送中文内容的时候,会出现乱码问题,此时,需要手动设置内容的编码格式
const http = require('http') const server = http.createServer() server.on('request', (req, res) => { // 定义一个字符串,包含中文的内容 const str = `您请求的 URL 地址是 ${req.url},请求的 method 类型为 ${req.method}` // 调用 res.setHeader() 方法,设置 Content-Type 响应头,解决中文乱码的问题 res.setHeader('Content-Type', 'text/html; charset=utf-8') 9 // res.end() 将内容响应给客户端 res.end(str) }) server.listen(80, () => { console.log('server running at http://127.0.0.1') })
url
响应不同的内容获取请求的 url
地址
设置默认的响应内容为 404 Not found
判断用户请求的是否为 /
或 /index.html
首页
判断用户请求的是否为 /about.html
关于页面
设置 Content-Type
响应头,防止中文乱码
使用 res.end()
把内容响应给客户端
const http = require('http') const server = http.createServer() server.on('request', (req, res) => { // 1. 获取请求的 url 地址 const url = req.url // 2. 设置默认的响应内容为 404 Not found let content = '404 Not found!
' // 3. 判断用户请求的是否为 / 或 /index.html 首页 // 4. 判断用户请求的是否为 /about.html 关于页面 if (url === '/' || url === '/index.html') { content = '首页
' } else if (url === '/about.html') { content = '关于页面
' } // 5. 设置 Content-Type 响应头,防止中文乱码 res.setHeader('Content-Type', 'text/html; charset=utf-8') // 6. 使用 res.end() 把内容响应给客户端 res.end(content) }) server.listen(80, () => { console.log('server running at http://127.0.0.1') })
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Get to know Node.js and talk about the modularity of node. For more information, please follow other related articles on the PHP Chinese website!