Home > Web Front-end > JS Tutorial > Get to know Node.js and talk about the modularity of node

Get to know Node.js and talk about the modularity of node

青灯夜游
Release: 2021-11-02 10:30:30
forward
1712 people have browsed it

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!

Get to know Node.js and talk about the modularity of node

Introduction to Node.js

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/

Node JavaScript running environment in .js

Get to know Node.js and talk about the modularity of node

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.

Installation of Node.js environment

Double-click the official homepage of Node.js (nodejs.org/en/) to download

Get to know Node.js and talk about the modularity of node

The difference between LTS version and Current version

① 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

Use the shortcut key (

Windows logo key R

) to open the run panel and enter cmd and press Enter directly to open the terminalOpen the terminal and enter the command

node –v

in the terminal to view the downloaded version

Shortcut keys in the terminal

① Use the

key to quickly locate the last executed command ② Use

tab

key can quickly complete the path ③ Use

esc

key to quickly clear the currently entered command ④ Enter the

cls

command , you can clear the terminal

Modularity

Modular concept:

    Modularization refers to when solving a complex problem, The process of dividing the system into several modules from top to bottom layer by layer
  • . For the entire system,

    modules are units that can be combined, decomposed and replaced ##Modularization in the programming field means

    abiding by fixed rules
  • , split a
  • large file

    into multiple small modules that are independent and interdependent to modularize the code Benefits

  • Improves the reusability of the code

    Improves the maintainability of the code
    • Can realize on-demand loading
  • Modularization in Node

Built-in modules (built-in modules are provided by

Node.js
    Officially provided, such as
  • fs

    , path, http, etc.) Custom modules (user-created Each

    .js
  • file is a custom module)
  • 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.

    You need to download it before using it
  • )
  • Use the
  • require
method to load the module

fs file system modulefs 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.

In JavaScript code, if you use the fs module to operate files, you need to import it first in the following way:

Read the contents of the specified file

Get to know Node.js and talk about the modularity of node 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)
 })
Copy after login

Write content to the specified file

2, fs.writeFile The syntax format of ()

Get to know Node.js and talk about the modularity of node

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('文件写入成功!')
 })
Copy after login

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.

Get to know Node.js and talk about the modularity of node

path path module

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

Get to know Node.js and talk about the modularity of node

Parameter interpretation:

• ...paths Sequence of path fragments

• Return value:


Code example

Get to know Node.js and talk about the modularity of node

##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 path

Code example

Get to know Node.js and talk about the modularity of node

3. path.extname() Gets the file extension in the path

Syntax format

Get to know Node.js and talk about the modularity of node

Parameter interpretation:

• path is a required parameter, a string representing a path

• Return: Return the obtained Extension string

****

Code example

1Get to know Node.js and talk about the modularity of node

Comprehensive case-clock Case

Requirements:

Split the page.html page in the material directory into three files, which are:

• index.css

• index.js

• index.html

material 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>
Copy after login

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, &#39;<link rel="stylesheet" href="./index.css">&#39;)
       .replace(regStcript, &#39;<script src="./index.js"></script>&#39;)
     fs.writeFile(path.join(__dirname, "./index.html"), newHTML, function (err) {
       if (err) {
         console.log("HTML文件写入失败!" + err.message)
       } else {
         console.log("HTML文件写入成功!")
       }
     })
   }
 })
Copy after login

http module

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

Use the

http module to create a Web server, you need to import it first:

const http = require(&#39;http&#39;)
Copy after login

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,它们都代表我们自己的这台电脑,在使用效果上没有任何区别
Copy after login

端口号

  • 在一台电脑中,可以运行成百上千个 web 服务

  • 每个web 服务 都对应一个唯一的端口号

  • 客户端发送过来的网络请求,通过端口号,可以被准确地交给对应的 web 服务 进行处理

1Get to know Node.js and talk about the modularity of node

创建web服务器

实现步骤和核心代码

  // 1. 导入 http 模块
  const http = require(&#39;http&#39;)
  // 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')
 })
Copy after login

req 请求对象

  const http = require(&#39;http&#39;)
  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')
 })
Copy after login

res 响应对象

在服务器的 request 事件处理程序中,如果想访问与服务器相关的数据和属性,可以使用如下方式

  server.on(&#39;request&#39;, function (req, res) {
    // res 是响应对象,它包含了与服务器相关的数据和属性
    // 例如:将字符串发送到客户端
  
    const str = `${req.url} -- ${req.method}`
    
    // res.end() 方法的作用
    // 向客户端发送指定的内容,并结束这次请求的处理过程
    res.end(str)
 })
Copy after login

解决中文乱码问题

当调用 res.end() 方法,向客户端发送中文内容的时候,会出现乱码问题,此时,需要手动设置内容的编码格式

  const http = require(&#39;http&#39;)
  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')
 })
Copy after login

根据不同的 url 响应不同的内容

核心实现步骤

  • 获取请求的 url 地址

  • 设置默认的响应内容为 404 Not found

  • 判断用户请求的是否为 //index.html 首页

  • 判断用户请求的是否为 /about.html 关于页面

  • 设置 Content-Type 响应头,防止中文乱码

  • 使用 res.end() 把内容响应给客户端

  const http = require(&#39;http&#39;)
  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') })
Copy after login

更多编程相关知识,请访问:编程视频!!

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template