Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the modularization of node in Node.js

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to understand the modularization of node in Node.js". In daily operation, I believe many people have doubts about how to understand the modularization of node in Node.js. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how to understand the modularization of node in Node.js"! Next, please follow the editor to study!

Introduction to Node.js

Concept: is a JavaScript runtime environment based on the Chrome V8 engine. [recommended: "nodejs tutorial"]

Node.js 's official website address: https://nodejs.org/zh-cn/

JavaScript runtime environment in Node.js

Note:

① browser is the front-end running environment of JavaScript.

② Node.js is the back-end running environment for JavaScript.

Cannot call DOM, BOM, etc., in ③ Node.js

API is built into the browser.

Installation of Node.js environment

Double-click the home page (nodejs.org/en/) of Node.js 's official website to download

The difference between LTS version and Current version

① LTS is a long-term stable version. For enterprise projects that pursue stability, it is recommended to install the LTS version of Node.js.

② Current is a fresh version of the new feature. For users who are keen to try new features, it is recommended to install the Current version of Node.js. However, the Current version is available

There can be hidden Bug or security vulnerabilities, so it is not recommended to use the Current version of Node.js in enterprise projects.

View the version number of the installed Node.js

Use the shortcut key (Windows logo key + R) to open the running panel, enter cmd and enter directly to open the terminal.

Open the terminal and enter the command node-v at the terminal to view the downloaded version

Shortcut keys in the terminal

① uses the ↑ key to quickly navigate to the last executed command

② uses the tab key to complete the path quickly.

③ uses the esc key to quickly clear commands that are currently entered

④ enter the cls command to clear the terminal

Modularization

Modular concept:

Modularization refers to the process of dividing the system into several modules layer by layer from top to bottom when solving a complex problem. For the whole system, the module is a unit that can be combined, decomposed and replaced.

Modularization in the field of programming is to follow the fixed rules of splitting a large file into independent and interdependent small modules.

The benefits of modularizing the code

Improve the reusability of the code

Improve the maintainability of the code

It can be loaded on demand.

Modularization in Node

Built-in modules (built-in modules are officially provided by Node.js, such as fs, path, http, etc.)

Custom module (every .js file created by the user is a custom module)

Third-party module (a module developed by a third party is not an official built-in module, nor is it a user-created custom module, which needs to be downloaded before use)

Use the require method to load the module

Fs file system module

The fs module is officially provided by Node.js and is used to manipulate files. It provides a series of methods and properties to meet the user's needs for file operation.

In the JavaScript code, if you use the fs module to manipulate the file, you need to import it in the following way:

Read the contents of the specified file

1. The syntax format of fs.readFile ()

Parameter interpretation:

Parameter 1: required parameter, string, indicating the path of the file.

Parameter 2: an optional parameter indicating the encoding format in which the file is read.

Parameter 3: a required parameter. After the file is read, the read result is obtained through the callback function.

Show:

/ / 1. Import the fs module to manipulate the file const fs = require ('fs') / / 2. Call the fs.readFile () method to read the file / / parameter 1: read the file's storage path / / parameter 2: the encoding format used when reading the file. Generally, utf8 / / parameter 3: callback function is specified by default. Get the result of read failure and success err dataStr fs.readFile ('. / files/11.txt', 'utf8', function (err, dataStr) {/ / 2.1print the result of failure / / if the read is successful, the value of err is null / / if the read fails, the value of err is the error object The value of dataStr is undefined / / console.log (err) / / console.log ('-') / / 2.2 the result of a successful print console.log (dataStr) / / determines whether the file was read successfully if (err) {return console.log ("failed to read the file!" + err.message)} console.log ("read file successfully!" + dataStr)}) write to the specified file

2. The syntax format of fs.writeFile ()

Parameter interpretation:

Parameter 1: a required parameter. You need to specify a string of file paths to indicate the storage path of the file.

Parameter 2: a required parameter indicating what to write.

Parameter 3: optional parameter indicating the format in which the contents of the file are written. The default value is utf8.

Parameter 4: required parameter, callback function after the file is written.

Show:

/ / 1. Import the fs file system module const fs = require ('fs') / / 2. Call the fs.writeFile () method to write the contents of the file / / Parameter 1: indicates the storage path of the file / / Parameter 2: indicates the content to be written / / Parameter 3: callback function fs.writeFile ('. / files/3.txt', 'ok123', function (err) {/ / 2.1 if the file is written successfully, the value of err is equal to null / / 2.2 if the file fails to write Then the value of err is equal to an error object console.log (err) / / 3 to determine whether the file was written successfully if (err) {return console.log ('file write failed!' + err.message)} console.log ('file written successfully!') })

The problem of fs Module-path dynamic splicing

When using the fs module to manipulate files, if the operation path provided is a relative path that begins with. / or.. /, it is easy to cause the problem of path dynamic splicing errors.

Reason: when the code is running, it will dynamically splice the full path of the manipulated file to the directory where the node command is executed.

Solution: when using the fs module to manipulate files, directly provide the complete path, do not provide a relative path at the beginning of. / or.. /, so as to prevent the problem of path dynamic splicing.

Path path module

Concept: a module provided officially by Node.js to handle paths

1. The path.join () method is used to concatenate multiple path fragments into a complete path string.

Grammatical format

Parameter interpretation:

.. sequence of paths path fragments

Return value:

Code example

Note: in the future, all operations involving path stitching will be handled using the path.join () method. Do not directly use + to concatenate strings.

2. Path.basename () gets the file name in the path

Parameter interpretation:

Required parameter for path, which represents a string of paths

Ext optional parameter, indicating the file extension

Return: represents the last part of the path

Code example

3. Path.extname () gets the file extension in the path

Grammatical format

Parameter interpretation:

Required parameter for path, which represents a string of paths

Return: returns the resulting extended name string

* Code example

Comprehensive case-clock case

Demand:

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

Index.css

Index.js

Index.html

Material page.html

Documenthtml,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;/* box projection * /-webkit-box-reflect: below px-webkit-gradient (linear, left top, left bottom, from (transparent), color-stop (%, transparent), to (rgba (,.)) }:: _ window.onload = function () {/ / timer SetInterval (() = > {var dt = new Date () var HH = dt.getHours () var mm = dt.getMinutes () var ss = dt.getSeconds () / / assign document.querySelector ("# HH") [xss_clean] = padZero (HH) document.querySelector ("# mm") [xss_clean] = padZero (mm) document.querySelector ("# ss") [xss_clean] = padZero (ss)} to the elements on the page every second )} / / Zero filling function function padZero (n) {return n >? N: "" + n}

The split code is as follows:

/ / Import / / Import fs file module const fs = require ("fs") / / Import path const path = require ("path") / / const {join} = require ("path/posix") pit: after typing the word resove code, this code will be automatically formed, resulting in an error. Comment it or delete it to run / / define the expression / /\ represents the escape character \ s match spaces (including newline characters, tab spaces),\ S non-spaces / / [] match any character in formula parentheses, * repeat or more Const regStyle = / [\ s\ S] * / const regStcript = / [\ s\ S] * / / read the file fs.readFile (path.join (_ _ dirname, ". / index.html"), "utf", function (err) Data) {/ / determine whether the file was read successfully if (err) {/ / failed to read the file console.log ("failed to read the file" + err.message)} else {/ / read the file successfully console.log ("read the file successfully" + data) / / after reading the file successfully Call the corresponding methods to parse the css, js, html content resoveCss (data) resoveJs (data) resoveHTML (data)} / write the html.css stylesheet function resoveCss (htmlStr) {/ / use const r = regStyle.exec (htmlStr) / / cnsole.log (r []) / / to extract the style string from the page Do further processing const newCss = r [] .replace (",") .replace (",") / / # Note: when writing a file, you need to create a file (such as index.css) first Then run node.\ clock.js on the terminal, and fs.writeFile (path.join (_ dirname, ". / index.css"), newCss, function (err) will be displayed in the stylesheet. Data) {if (err) {console.log ("CSS style file writing failed" + err.message)} else {console.log ("CSS style file written successfully")})} / / write html.js stylesheet function resoveJs (htmlJs) {/ / exec retrieval string The matching const r = regStcript.exec (htmlJs) / / r [] of the expression gets the element const newJS = r [] .replace ("") that is indexed after a successful match "). Replace (", ") fs.writeFile (path.join (_ dirname,". / index.js "), newJS, function (err, data) {if (err) {console.log (" JS file written successfully "+ err.message)} else {console.log (" JS file written successfully! ") }})} / / write index.html stylesheet function resoveHTML (html) {const newHTML = html. Replace (regStyle,'). Replace (regStcript,') fs.writeFile (path.join (_ _ dirname, ". / index.html"), newHTML, function (err) {if (err) {console.log ("HTML file write failed!" + err.message)} else {console.log ("HTML file written successfully!") })}) http module

Concept: the module used to create a web server. Through the http.createServer () method provided by the http module, you can easily turn an ordinary computer into a Web server, thus providing Web resource services to the outside world.

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

Const http = require ('http') the role of the http module:

1. The difference between a server and an ordinary computer is that web server software is installed on the server.

2. Based on the http module provided by Node.js, I can easily handwrite a server software through a few simple lines of code to provide web services.

Server-related concepts ip address

The IP address is the unique address of every computer on the Internet, so the IP address is unique.

The format of the IP address: it is usually expressed as (a.b.c.d) in dotted decimal, where a _ is a decimal integer between 0,255.

For example: IP address in dotted decimal (192.168.1.1)

Domain name and domain name server

Although the IP address can uniquely mark the computer on the network, the IP address is a long string of numbers, which is not intuitive and difficult to remember, so people invented another character-based address scheme, the so-called domain name address (Domain Name).

There is an one-to-one correspondence between IP address and domain name, which is stored in a computer called domain name server (DNS,Domain name server). Users only need to access the corresponding server through the domain name that is easy to remember, and the corresponding conversion work is realized by the domain name server. Therefore, a domain name server is a server that provides translation services between IP addresses and domain names.

Note:

1. Computers on the Internet can also work properly by simply using the `IP address'. But with the blessing of domain names, the world of the Internet can become more convenient. During the development and testing, the corresponding domain name of 127.0.0.1 is localhost, and they all represent our own computer, and there is no difference in port number in use.

Hundreds of web services can be run on a single computer

Each web service corresponds to a unique port number

The network request sent by the client can be accurately handed over to the corresponding web service for processing through the port number.

Create a web server

Implementation steps and core code

/ / 1. Import the http module const http = require ('http') / / 2. Create a web server instance / / call the http.createServer () method to quickly create a web server instance const server = http.createServer () / / 3. Bind the request event to the server instance / / bind the request event to the server instance to listen to the network requests sent by the client / / bind a request event server.on ('request', function (req, res) {console.log (' Someone visit our web server.')}) / / 4 for the server using the .on () method of the server instance. Call the .server () method of the server instance to start the current web server instance server.listen (8080, function () {console.log ('server running at http://127.0.0.1:8080')}) req request object const http = require (' http') const server = http.createServer () / / req is the request object Contains client-related data and attributes server.on ('request', (req, res) = > {/ / req.url is the URL address of the client request const url = req.url / / req.method is the method type of the client request const method = req.method const str = `Your request url is ${url}, and request method is ${method} `console.log (str) / / call the res.end () method Respond some content to the client res.end (str)}) server.listen (80, () = > {console.log ('server running at http://127.0.0.1')}))

Res response object

In the server's request event handler, if you want to access server-related data and properties, you can use the following

Server.on ('request', function (req, res) {/ / res is the response object, which contains server-related data and attributes / / for example: send the string to the client const str = `${req.url}-- ${req.method}` / / res.end () method / / send the specified content to the client And end the processing process of this request res.end (str)}) solve the problem of Chinese garbled code

When the res.end () method is called to send Chinese content to the client, the problem of garbled code will occur. At this time, you need to manually set the encoding format of the content.

Const http = require ('http') const server = http.createServer () server.on (' request', (req, res) = > {/ / define a string containing Chinese content const str = `The URL address you requested is ${req.url}, the method type of the request is ${req.method} `/ / call the res.setHeader () method, and set the Content-Type response header Solve the problem of Chinese garbled code res.setHeader ('Content-Type',' text/html) Charset=utf-8') 9 / / res.end () responds the content to the client res.end (str)}) server.listen (80, () = > {console.log ('server running at http://127.0.0.1')})) responds to different content core implementation steps according to different url

Get the requested url address

Set the default response content to 404 Not found

Determine whether the user requested is / or / index.html home page

Determine whether the user requested is / about.html about the page

Set Content-Type response header to prevent Chinese garbled

Use res.end () to respond to the content to the client

Const http = require ('http') const server = http.createServer () server.on (' request', (req, res) = > {/ / 1. Get the requested url address const url = req.url / / 2. Set the default response content to 404 Not found let content = '404 Not responses' / / 3. Determine whether the user requested is / or / index.html home page / / 4. Determine whether the user requested / about.html about the page if (url ='/'| | url ='/ index.html') {content = 'home'} else if (url ='/ about.html') {content = 'about the page'} / / 5. Set the Content-Type response header to prevent Chinese garbled res.setHeader ('Content-Type',' text/html; charset=utf-8') / / 6. Use res.end () to respond to the client res.end (content)}) server.listen (80, () = > {console.log ('server running at http://127.0.0.1')})) so far, the study on "how to understand the modularization of node in Node.js" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report