Create by jsliang on 2018-11-8 13:42:42
Recently revised in 2018-12-23 21:59:20
Hello friends, if you think this article is good, remember to click a “like” or “star”, your “like” and “star” are the motivation for me to write more and more wonderful articles! Making the address
Thanks to the refactoring of jsliang’s document library, some links to this article may not work, and Jsliang does not have the energy to maintain the old articles in Gold. Sorry. For those who want to get the latest posts, click on the GitHub address above and go to the document library to view the adjusted posts.
Key content of this paper
- Node Basics – Lay the foundation of Node by learning the basics of Node
- Node API – Enables the service provisioning API for front-end calls
- Node connecting to MySQL – Install MySQL using NPM to connect to the database
- Node actual – Enterprise official website starts from 0, to build the enterprise official website that can register, log in and leave messages
- Node deployment – How to deploy a cloud server so that people can view your website
Extended link to this article
- Node Use of deployment projects, cloud servers, and domain names: links
- Download the Node base code at: link
- This article Node production code download address: link
Demonstration of finished products in this paper
- Node project demo: Jsliang Front-end LTD
A directory
No toss of the front end, and salted fish what’s the difference
The preface
Returns the directory
Main objectives of this paper:
- Integrate Node foundation, deepen jsliang learning understanding of Node, and facilitate future review.
- Integrate Node tools to find out which tools are useful for Node development.
- This is a reference for beginners of Node. If you have any questions, please contact the QQ group:
798961601
In the consultation.
Three basic
Returns the directory
Great oaks rise from little acorns, but the foundation must rise by itself.
3.1 HTTP – Start the Node journey
Returns the directory
No more words, first on the code:
01_http.js
Var HTTP = require();"http"); /** * req (request) * res (response) */ http.createserver ()function(req, res) {// set the HTTP header, status code to 200, file type to HTML, character set to UTf8"Content-Type": "text/html; charset=UTF-8"}); // Print the value to the page res.write('<h1 style="text-align:center">Hello NodeJS</h1>'); Res.end (); }).listen(3000); // The listening portCopy the code
So, how do we use this code?
First, copy and paste the above code into 01_http.js. Then, start the VS Code terminal: Ctrl + ~. Next, type node 01_http.js and press Enter. Finally, open localhost:3000:
OK, that’s done. Now let’s go through the code above:
- First, we need to turn on fairy mode. Oh, no, HTTP mode. As we all know, old-name back-end languages like PHP require Apache or Nginx to enable HTTP services. However, our Node does not need:
var http = require("http");
Copy the code
- Then, enable the HTTP service and set the port to be enabled:
/** * req (request) * res */ http.createserver (request)function(req, res) { // ... Step 3 Code}).listen(3000); // The listening portCopy the code
- Next, we set the HTTP header, print the value to the page, and finish the response:
// Set the HTTP header, status code to 200, file type to HTML, and character set to UTf8"Content-Type": "text/html; charset=UTF-8"}); // Print the value to the page res.write('<h1 style="text-align:center">Hello NodeJS</h1>'); Res.end ();Copy the code
- The lastSo, we type it into the browser
http://localhost:3000/
, will access the Node service we started to render the page to the page.
At this point, are you starting your own Node journey?
3.2 the URL module
Returns the directory
What is the URL module? Let’s start Node mode on the console (terminal) and print out the URL to see:
It has Url, Parse, resolve, resolveObject, format, Url, URLSearchParams, domainToASCII, and domainToUnicode modules. So, what do these modules do?
No more words, first on the code:
02_url.js
Var url = require();"url"); Var HTTP = require(); // 2."http"); /** * req (request) * res (response) */ http.createserver ()function(req, res) {// 4. Get server request /** * access address: http://localhost:3000/? UserName =jsliang&userAge=23 * If you execute console.log(req.url), it will execute twice and return the following information: * /? UserName =jsliang&userAge=23 */ / /favicon.ico */ / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /if(req.url ! ="/favicon.ico"Parse method using url /** * Parse method takes two arguments: * The first argument is the address * the second argument istrue*/ var result = url.parse(req.true);
console.log(result);
/**
* Url {
* protocol: null,
* slashes: null,
* auth: null,
* host: null,
* port: null,
* hostname: null,
* hash: null,
* search: '? userName=jsliang&userAge=23',
* query: { userName: 'jsliang', userAge: '23' },
* pathname: '/',
* path: '/? userName=jsliang&userAge=23',
* href: '/? userName=jsliang&userAge=23'} */ console.log(result.query.userName); // jsliang console.log(result.query.userAge); // writeHead(200, {writeHead(200, {writeHead(200, {writeHead)})"Content-Type": "text/html; charset=UTF-8"}); // Print the value to the page res.write('<h1 style="text-align:center">Hello NodeJS</h1>'); Res.end (); }).listen(3000);Copy the code
In the code above:
First, we introduce the protagonist URL module of this chapter:
Var url = require();"url");
Copy the code
Then, we introduce the HTTP module:
Var HTTP = require(); // 2."http");
Copy the code
Next, we create the HTTP module, because the URL listens, we need the HTTP module enabled:
/** * req (request) * res (response) */ http.createserver ()function(req, res) { // ... Res.writehead (200, {writeHead(200, {writeHead(200, {writeHead(200, {writeHead)});"Content-Type": "text/html; charset=UTF-8"}); // Print the value to the page res.write('<h1 style="text-align:center">Hello NodeJS</h1>'); Res.end (); }).listen(3000);Copy the code
Finally, we visit the address we give: http://localhost:3000/? UserName =jsliang&userAge=23 and see how the URL parse module uses it.
// 4. Obtain the server request /** * Access address: http://localhost:3000/? UserName =jsliang&userAge=23 * If you execute console.log(req.url), it will execute twice and return the following information: * /? UserName =jsliang&userAge=23 */ / /favicon.ico */ / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /if(req.url ! ="/favicon.ico"Parse method using url /** * Parse method takes two arguments: * The first argument is the address * the second argument istrue*/ var result = url.parse(req.true);
console.log(result);
/**
* Url {
* protocol: null,
* slashes: null,
* auth: null,
* host: null,
* port: null,
* hostname: null,
* hash: null,
* search: '? userName=jsliang&userAge=23',
* query: { userName: 'jsliang', userAge: '23' },
* pathname: '/',
* path: '/? userName=jsliang&userAge=23',
* href: '/? userName=jsliang&userAge=23' }
*/
console.log(result.query.userName); // jsliang
console.log(result.query.userAge); // 23
}
Copy the code
From this, we can see that we can get the path field we want by using query.
Of course, the above only explains parse, so you can clean out all the code in the if statement. Then, enter the following to learn more about the URL module:
- Url module all contents:
console.log(url); /** * Console: {Url: [Function: Url], parse: [Function: urlParse], // Resolve: [Function: urlParse] ResolveObject: [Function: urlResolveObject], format: [Function: urlResolveObject] [Function: url], URLSearchParams: [Function: url], URLSearchParams: [Function: url] URLSearchParams], domainToASCII: [Function: domainToASCII], domainToUnicode: [Function: domainToUnicode] } */Copy the code
- How to use Parse
console.log(url.parse("http://www.baidu.com")); /** * Console: Url {protocol:'http:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com'.hash: null,
search: null,
query: null,
pathname: '/',
path: '/',
href: 'http://www.baidu.com/'} * /Copy the code
- Parse with parameters:
console.log(url.parse("http://www.baidu.com/new?name=zhangsan")); /** * Console: Url {protocol:'http:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com'.hash: null,
search: '? name=zhangsan',
query: 'name=zhangsan',
pathname: '/new',
path: '/new? name=zhangsan',
href: 'http://www.baidu.com/new?name=zhangsan'} * /Copy the code
format
The use of:
console.log(url.format({
protocol: 'http:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com'.hash: null,
search: '? name=zhangsan',
query: 'name=zhangsan',
pathname: '/new',
path: '/new? name=zhangsan',
href: 'http://www.baidu.com/new?name=zhangsan'// Console :// http://www.baidu.com/new?name=zhangsanCopy the code
resolve
The use of:
console.log(url.resolve("http://www.baidu.com/jsliang"."Leung Jun-wing")); // Console :// http://www.baidu.com/ Liang JunrongCopy the code
Url here, of course, we are only a primer, more also look at the website API: url | Node. Js v10.14.1 document
3.3 CommonJS
Returns the directory
- What is CommonJS?
CommonJS is a specification for the presentation of JS. With no module system, few standard libraries, and a lack of package management tools, CommonJS came into being and wanted JS to run anywhere, not just in the browser. So as to achieve Java, C#, PHP these back-end languages have the ability to develop large applications.
- CommonJS application?
- Server-side JavaScript applications. (Node. Js)
- Command line tools
- Desktop graphical interface applications.
- CommonJS and Node.js?
CommonJS is the standard for modularity, and Node.js is the implementation of CommonJS (modularity).
- Modularity in Node.js?
- In Node, modules are divided into two types: one is the module provided by Node, called the core module; The second is the user written module, become the file module. The core module is compiled into binary execution files during the compilation of Node source code, so it has the fastest loading speed, such as: HTTP module, URL module, FS module; The file module is loaded dynamically at run time, which requires complete road strength analysis, file positioning, compilation and execution process… So it’s going to be slower than the core module.
- We can separate the public functionality into a separate JS file and export modules via exports or module.exports if needed and import them via require.
Now let’s look at modularity and exports/require in Node in three ways.
Let’s look at the directory first:
Method one:
First of all, Js, node_modules/ 03_tool-add.js, node_modules/03_tool-multiply. Js, node_modules/jsliang-module/tools.js We’ll leave package.json out for now and see how it’s automatically generated later.
Js: in 03 _tool – add.
03_tool-add.js
Var tools = {add: (... numbers) => {let sum = 0;
for (let number in numbers) {
sum += numbers[number];
}
returnsum; } /** * 2. * exports. STR = exports. STR; * module.exports = str; * the difference: * exports is a helper tool. * If module.exports is empty, then all properties and methods collected by exports are Exports */ // exports // / exports // / STR ="jsliang is very good!";
// exports.str = str; // { str: 'jsliang is very good! '} // module. Exports = tools;Copy the code
So, what does the above code mean? In the first step, we defined the tool library Tools. In the second step, we exported tools via modules.exports. So, we can use 03_commonjs.js with require import:
var http = require("http");
var tools1 = require('./03_tool-add');
http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "text/html; charset=UTF-8"
});
res.write('<h1 style="text-align:center">Hello NodeJS</h1>'); console.log(tools1.add(1, 2, 3)); / * * * the Console: * 6 * 6 * Remember that while Node is running, it requests twice, * http://localhost:3000/ once, * http://localhost:3000/favicon.ico for a second * / res in the end (); }).listen(3000);Copy the code
This completes the first use of exports and require.
Method 2:
When we have a lot of modules, we need a directory to store them. Node is a good example of this, as it allows us to put all of them in a directory called node_modules.
So, let’s create a 03_tool-multiply. Js file in node_modules. The contents are as follows:
03_tool-multiply.js
var tools = { multiply: (... numbers) => {let sum = numbers[0];
for (let number in numbers) {
sum = sum * numbers[number];
}
return sum;
}
}
module.exports = tools;
Copy the code
In terms of citations, we just need to pass:
// If Node does not find tool.js in its current directory, it will look for var tools2 = require(node_modules)'03_tool-multiply');
console.log(tools2.multiply(1, 2, 3, 4));
Copy the code
In this way, you can successfully import the 03_tool-multiply. Js file.
Method 3:
Node_modules would be cluttered with all the single files, so we should define our own module, jsliang-module, and store our tools.js in that directory:
jsliang-module/tools.js
var tools = { add: (... numbers) => {let sum = 0;
for (let number in numbers) {
sum += numbers[number];
}
returnsum; }, multiply: (... numbers) => {let sum = numbers[0];
for (let number in numbers) {
sum = sum * numbers[number];
}
return sum;
}
}
module.exports = tools;
Copy the code
In this way, we have defined our toolkit. However, if we pass var tools3 = require(‘jsliang-module’); When we import it, we will find that it reports error, so we should generate a package.json from the jsliang-module directory with the following command line
PS E:\MyWeb\node_modules\jsliang-module> npm init –yes
This gives you package.json in jsliang-module. We can reference it in 03_commonjs.js:
03_CommonJS.js
var http = require("http");
var tools1 = require('./03_tool-add'); // If Node does not find tool.js in its current directory, it will look for var tools2 = require(node_modules)'03_tool-multiply'); /** * use package.json to reference files * 1. 2. Package. json file tells the program that the entry file is:"main": "tools.js"/ var tools3 = require(); / var tools3 = require();'jsliang-module');
http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "text/html; charset=UTF-8"
});
res.write('<h1 style="text-align:center">Hello NodeJS</h1>'); console.log(tools1.add(1, 2, 3)); console.log(tools2.multiply(1, 2, 3, 4)); console.log(tools3.add(4, 5, 6)); / * * * the Console: * 6 * 24 * 15 * 6 * 24 * 15 * 6 * 24 * 15 * * http://localhost:3000/favicon.ico for a second * / res in the end (); }).listen(3000);Copy the code
There are three ways to look at the posture of various exports and require and the concept of Node modularity
References:
- CommonJS standard garden | blog – Little Bird
- How to understand CommonJS and AMD/CMD! | blog garden – convenient to review later
- Es6 – Indestruct parameters and expansion operators (…) Garden – ghostwu | blog
3.4 package with NPM
Returns the directory
In addition to its own core modules, Node can also customize modules and use third-party modules. Third-party modules in a Node are composed of packages, which can be used to centrally manage a group of modules that depend on each other.
So, if we need to use some third-party modules, where should we go?
- Baidu. Baidu to find the corresponding content of the third-party module you need to install.
- NPM’s official website. If you already know the name of the package or what the package does. You should find the packages you want to install faster by searching directly on the NPM website.
So, what is NPM? NPM is the largest open source ecosystem in the world. We can download a variety of packages through NPM. When we install Node, it will give you NPM by default.
npm -v
: View the NPM version.npm list
: Check which NPM packages are installed in the current directory.NPM info module
: View the version and content of the module.NPM I Module @ Version number
: Installs the specified version of the module.
You may need to know some basics of NPM when using the NPM installation package on a regular basis:
i
/install
: the installation. useinstall
Or short for thati
“Indicates that you want to download the package.uninstall
: unloading. If you find that you are no longer using this module, you can pass ituninstall
Uninstall it.g
: Global installation. Indicates that the package will be installed on your computer and you can use it anywhere on the computer.--save
/-S
: The name and version number of the package installed in this way are displayed inpackage.json
In thedependencies
In the.dependencies
It needs to be published in the build environment. Such as:ElementUI
It’s needed after deployment, so pass-S
Form to install.--save-dev
/-D
: The name and version number of the package installed in this way are displayed inpackage.json
In thedevDependencies
In the.devDependencies
Only used in development environments. Such as:gulp
It’s just a tool to compress code and package it. It’s not needed at runtime, so it passes-D
Form to install.
Example:
cnpm i webpack-cli -D
npm install element-ui -S
So, how do we manage so many NPM packages? The answer is package.json. If we need to create package.json, we just need to generate it in the specified package management directory (e.g. Node_modules) with the following names:
npm init
: Create the following stepspackage.json
.npm init --yes
: Quick createpackage.json
Of course, because of the domestic network environment, sometimes through NPM download package, may be slow or directly broken, this time to install Taobao NPM mirror: CNPM
npm install -g cnpm --registry=https://registry.npm.taobao.org
3.5 FS file management
Returns the directory
In this chapter, we will talk about fs file management:
To quickly find one of the following, use Ctrl + F
fs.stat
Check for files or directoriesfs.mkdir
Create a directoryfs.writeFile
Create write filefs.appendFile
Additional documentsfs.readFile
Read the filefs.readdir
Read the directoryfs.rename
renamefs.rmdir
Delete the directoryfs.unlink
Delete the file
File directory for this section:
First, we check whether a file or directory is being read by fs.stat:
05_fs.js
// 1. fs.stat
let fs = require('fs');
fs.stat('index.js', (error, stats) => {
if(error) {
console.log(error);
return false;
} else{ console.log(stats); /** * Console: * Stats {* dev: 886875, * mode: 33206, * nlink: 1, * uid: 0, * gid: 0, * rdev: 0, * blksize: undefined, * ino: 844424931461390, * size: 284, * blocks: undefined, * atimeMs: 1542847157494, * mtimeMs: 1543887546361.2158, * ctimeMs: 1543887546361.2158, * birthtimeMs: 1542847157493.663, * atime: 2018-11-22t00:39:17.494z, * birthtime: 2018-12-04t00:39:06.361z, * birthtime: 2018-12-04t00:39:06.361z, * birthtime: 2018-12-04t00:39:06.361z, * birthtime: 2018-12-04t00:39:06.361z, * birthtime: 2018-12-04t00:39:06.361z, * birthtime: 2018-11-22t00:39:17.494z} */ console.log${stats.isFile()}`); // Console: file:trueThe console. The log (` directory:${stats.isDirectory()}`); // Console: directory:false
return false; }})Copy the code
With the information printed out of the Console, we have a basic understanding of the function of fs.stat.
Then, we try to create a directory with fs.mkdir:
05_fs.js
// 2. fs.mkdir
let fs = require('fs'); /** * receive parameter * path - path of the directory to be created * mode - directory permission (read/write permission), default 0777 * callback - callback, pass error parameter err */ fs.mkdir('css', (err) => {
if(err) {
console.log(err);
return false;
} else {
console.log("Directory created successfully!"); // Console: directory created successfully! }})Copy the code
With node 05_fs.js, we find an extra CSS folder in the directory.
So, there is create there is delete, create directories how to delete? Fs.rmdir:
05_fs.js
// 8. fs.rmdir
let fs = require('fs'); /** * receive parameter * path - path of the directory to be created * mode - directory permission (read/write permission), default 0777 * callback - callback, pass error parameter err */ fs.rmdir('css', (err) => {
if(err) {
console.log(err);
return false;
} else {
console.log("Directory created successfully!"); // Console: directory created successfully! }})Copy the code
Using node 05_fs.js, we find that the CSS folder in the directory has been deleted.
Next, we create a writeFile with fs.writeFile:
05_fs.js
// 3. fs.writeFile
let fs = require('fs'); / filename (String) file name * * * * data (String | Buffer) to be written content, can be a String or Buffer data. * · Encoding (String) This parameter is optional. The default'utf-8'When data is a buffer, the value should be ignored. * · mode (Number) File read/write permission. Default: 438. * · flag (String) Default value'w'. * callback {Function}; */ fs.writeFile('index.js'.'Hello jsliang', (err) => {
if(err) {
console.log(err);
return false;
} else {
console.log('Write successful! '); }})Copy the code
It is worth noting that this is done by emptying all the data in the original file and then adding the phrase Hello jsliang. That is, if it exists, it overwrites. If it does not exist, it creates.
If you are interested, you can use fs.unlink to delete files, again without going into too much detail.
Since the above is an overwrite file, do you append files? Yes, use fs.appendFile instead:
05_fs.js
// 4. fs.appendFile
let fs = require('fs');
fs.appendFile('index.js'.'This is the text to append.', (err) => {
if(err) {
console.log(err);
return false;
} else {
console.log("Additional success"); }})Copy the code
In this way, we have succeeded in adding a paragraph to index.js so that it becomes:
index.js
The Hello jsliang text is what you want to appendCopy the code
Above, we have done: add, modify, delete operations. Then you must be familiar with what the next step is:
fs.readFile
Read the filefs.readdir
Read the directory
05_fs.js
let fs = require('fs');
// 5. fs.readFile
fs.readFile('index.js', (err, data) => {
if(err) {
console.log(err);
return false;
} else {
console.log("Read file successfully!"); console.log(data); // Console: // Read file successfully! // <Buffer 48 65 6c 6c 6f 20 6a 73 6c 69 61 6e 67 e8 bf 99 e6 ae b5 e6 96 87 e6 9c ac e6 98 af e8 a6 81 e8 bf bd e5 8a A0 e7 9a 84 E5 86 85 E5 ae b9>}}) // 6.fs. readdir'node_modules', (err, data) => {
if(err) {
console.log(err);
return false;
} else {
console.log("Directory read successfully!"); console.log(data); // Console: // Read directory successfully! / / /'03_tool-multiply.js'.'jsliang-module']}})Copy the code
As above, we successfully read the file and read the directory.
Finally, let’s review our initial goal:
Fs. writeFile Creates a file to be written 4. Fs. appendFile Apends files 5. Fs. readFile Reads files 6 Read a directory 7.fs. rename Rename 8.fs. rmdir Delete a directory 9.fs. unlink Delete a file
Good, all we have left is to rename:
05_fs.js
let fs = require('fs'); // 7.fs.rename Rename fs.rename('index.js'.'jsliang.js', (err) => {
if(err) {
console.log(err);
return false;
} else {
console.log("Renaming success!"); }})Copy the code
Of course, if fs.rename also has a more exciting function: cut
05_fs.js
let fs = require('fs'); // 7.fs.rename Rename fs.rename('jsliang.js'.'node_modules/jsliang.js', (err) => {
if(err) {
console.log(err);
return false;
} else {
console.log("Cut!"); }})Copy the code
OK, that’s all done, now the directory is:
3.6 the fs case
Returns the directory
In the previous chapter, we looked at fs file management. So, here, we try to use FS to do a little something:
06_fsDemo.js
/** * 1.fs. stat Check whether it is a file or a directory * 2.fs. mkdir Create a directory * 3.fs. writeFile Create write files * 4.fs. appendFile Append files * 5.fs. readFile Read files * 6.fs. readdir Read directory * 7.fs. rename Rename * 8.fs. rmdir Delete directory * 9.fs. unlink Delete file */ // 1. Create the upload directory on the server // 2. Find all the directories under the HTML directory and print them outlet fs = require('fs'); // Upload the image to fs.stat('upload', (err, stats) => {// Check whether there is a upload directoryif(err) {// if there is no fs.mkdir('upload', (error) => {
if(error) {
console.log(error);
return false;
} else {
console.log("Upload directory created successfully!"); }})}else{// if there is console.log(stats.isdirectory ()); console.log("With the Upload directory, you can do more!"); }}) // Read all files in the directory fs.readdir('node_modules', (err, files) => {
if(err) {
console.log(err);
return false;
} else{// determine whether it is a directory or a folder console.log(files);let filesArr = [];
(functionGetFile (I) {// Loop endsif(I == files.length) {// Print out all directories console.log("Catalogue:");
console.log(filesArr);
return false; } // Check whether the directory is a file or a folder fs.stat('node_modules/' + files[i], (error, stats) => {
if(stats.isDirectory()) { filesArr.push(files[i]); } // Call getFile(I +1) recursively; }}})}) (0))Copy the code
3.7 the fs flow
Returns the directory
Without further further, let’s look at the FS stream and its reads:
// create fs const fs = require('fs'); // Read the file in stream modelet fileReadStream = fs.createReadStream('index.js'); // Number of readsletcount = 0; // Save the datalet str = ' '; // Start reading filereadStream.on ('data', (chunk) => {
console.log(`${++count}To receive:${chunk.length}`); // Console: 1 received: 30 STR += chunk; }) filereadStream.on (filereadStream.on)'end', () => {
console.log("- end -"); console.log(count); console.log(str); // Console: -- end -- // 1 //"Hello World!"); }) // Failed to read filereadStream.on ('error', (error) => {
console.log(error);
})
Copy the code
In this case, we create a read stream through the FS module’s createReadStream, and then read the file index.js, thus finally output in the console:
1 Received: 259 -- End -- 1 console.log("Better to have no books than to believe in them; Look at the code. Delete these files.");
console.log("Better to have no books than to believe in them; Look at the code. Delete these files.");
console.log("Better to have no books than to believe in them; Look at the code. Delete these files.");
Copy the code
The three lines of console.log() are the text of index.js.
Then, we try a dirty deposit:
let fs = require('fs');
let data = 'console.log("Hello World! I want to store the data!" ) '; // Create a writable stream and write it to the file index.jslet writeStream = fs.createWriteStream('index.js'); Writestream.write (data,'utf8'); Writestream.end (); writeStream.on('finish', () => {
console.log('Write done! '); // Console: write complete});Copy the code
If we open index.js, we’ll see that the contents are changed to console.log(“Hello World! I want to store the data!” ), in turn, we read and write in the form of streams.
3.8 Creating a Web Server
Returns the directory
Here, we create a Web server using the HTTP module, URL module, PATH module, and FS module.
What is a Web server? A Web server generally refers to a Web server, which is a program that resides on a certain type of computer on the Internet. It can serve documents to Web clients such as browsers, and can also place Web site files for the world to browse. You can place data files for the world to download. The three most popular Web servers are Apache, Nginx, and IIS.
Next, we use Node to create a Web service:
08_WebService.js
// Import the HTTP modulelet http = require("http"); // Introduce the fs modulelet fs = require("fs"); Http.createserver ((req, res) => {// Get the response pathletpathName = req.url; // The default load pathif (pathName == "/") {// Default loaded home page pathName ="index.html"; } // Filter /favicon.ico requestsif(pathName ! ="/favicon.ico") {// get index.html fs.readfile (08_WebService)"./08_WebService/" + pathName, (err, data) => {
if(err) {// If this file does not exist console.log("404 Not Found!");
fs.readFile('./08_WebService/404.html', (errorNotFound, dataNotFound) => {
if(errorNotFound) {
console.log(errorNotFound);
} else {
res.writeHead(200, {
"Content-Type": "text/html; charset='utf-8'"}); Res.write (dataNotFound); Res.end (); }})return;
} else{// return the file // set the request header res.writeHead(200, {"Content-Type": "text/html; charset='utf-8'"}); Res.write (data); Res.end (); }}); } }).listen(8080);Copy the code
In this case, we type localhost:8080 in the browser and see:
It loads the entire index. HTML file, and doesn’t even include CSS? So, next, we’ll dynamically load HTML, CSS, and JS:
08_WebService.js
// Import the HTTP modulelet http = require("http"); // Introduce the fs modulelet fs = require("fs"); // Import the URL modulelet url = require("url"); // Import the path modulelet path = require("path"); Http.createserver ((req, res) => {// Get the response pathletpathName = url.parse(req.url).pathname; // The default load pathif (pathName == "/") {// Default loaded home page pathName ="index.html"; } // Get the file name extensionletextName = path.extname(pathName); // Filter /favicon.ico requestsif(pathName ! ="/favicon.ico") {// get index.html fs.readfile (08_WebService)"./08_WebService/"+ pathName, (err, data) => {// If the file does not existif (err) {
console.log("404 Not Found!");
fs.readFile(
"./08_WebService/404.html",
(errorNotFound, dataNotFound) => {
if (errorNotFound) {
console.log(errorNotFound);
} else {
res.writeHead(200, {
"Content-Type": "text/html; charset='utf-8'"}); Res.write (dataNotFound); Res.end (); }});return; } // Return this fileelse{// Get the file typeletext = getExt(extName); // Set the request header res.writeHead(200, {"Content-Type": ext + "; charset='utf-8'"}); Res.write (data); Res.end (); }}); } }).listen(8080); GetExt = (extName) => {switch(extName) {case '.html': return 'text/html';
case '.css': return 'text/css';
case '.js': return 'text/js';
default: return 'text/html'; }}Copy the code
So, when we request again, the browser will say:
Of course, we only simulated HTML, CSS, js file types above, we need to simulate more file types:
08_ext.json
Please click the link above for code detailsCopy the code
In the json file above, we define the various file types. At the moment, the file directory looks like this:
At this point, we need to modify our JS file to accommodate multiple requests and responses:
08_WebService.js
// Import the HTTP modulelet http = require("http"); // Introduce the fs modulelet fs = require("fs"); // Import the URL modulelet url = require("url"); // Import the path modulelet path = require("path"); Http.createserver ((req, res) => {// Get the response pathletpathName = url.parse(req.url).pathname; // The default load pathif (pathName == "/") {// Default loaded home page pathName ="index.html"; } // Get the file name extensionletextName = path.extname(pathName); // Filter /favicon.ico requestsif(pathName ! ="/favicon.ico") {// get index.html fs.readfile (08_WebService)"./08_WebService/"+ pathName, (err, data) => {// If the file does not existif (err) {
console.log("404 Not Found!");
fs.readFile(
"./08_WebService/404.html",
(errorNotFound, dataNotFound) => {
if (errorNotFound) {
console.log(errorNotFound);
} else {
res.writeHead(200, {
"Content-Type": "text/html; charset='utf-8'"}); Res.write (dataNotFound); Res.end (); }});return; } // Return this fileelse{// Get the file typeletext = getExt(extName); console.log(ext); // Set the request header res.writeHead(200, {"Content-Type": ext + "; charset='utf-8'"}); Res.write (data); Res.end (); }}); } }).listen(8080); GetExt = (extName) => {//readFile is an asynchronous operation, so you need to usereadFileSync
let data = fs.readFileSync('./08_ext.json');
let ext = JSON.parse(data.toString());
return ext[extName];
}
Copy the code
So we made a simple Web server.
3.9 Non-blocking I/O event driven
Returns the directory
A server-side language, such as Java, PHP, or.NET, creates a new thread for each client connection. Instead of creating a new thread for each client connection, Node uses only one thread. When a user is connected, an internal event is triggered, making Node applications macroscopically parallel through non-plug I/O, event-driven mechanisms. Using Node, a server with 8GB of memory, it can handle over 40,000 user connections simultaneously.
In this chapter, the main solution is:
- What is non-blocking I/O for a Node?
- What is the Node Events module?
First, in our normal programming, we want the program to be written line by line as we wish:
09_io.js
console.log("1");
console.log("2");
console.log("3");
/**
* Console:
* 1
* 2
* 3
*/
Copy the code
However, it backfired. We sometimes execute asynchronous methods (functions) :
09_io.js
console.log("1");
// console.log("2");
let fs = require('fs');
getExt = () => {
fs.readFile('08_ext.json', (err, data) => {
console.log("2");
})
}
getExt();
console.log("3");
/**
* Console:
* 1
* 3
* 2
*/
Copy the code
In the above code, because fs.readFile is an asynchronous function of Node. So, the program executes 1 and 3 first, and then the two parts of fs.readfile are executed last.
Here, you can see that Node does not have a logical error in one piece of code that prevents other code from running.
This leads to a problem: Step 3 May not get the execution results of Step 2! This is the non-plugging I/O driver for Node. So, is there any way we can solve this problem? Some!
- Through the callback function
- Through the Node
events
The module
First, let’s solve the asynchronous problem with a callback function:
09_io.js
let fs = require("fs");
getExt = (callback) => {
fs.readFile('08_ext.json', (err, data) => {
callback(data);
})
}
getExt( (result) => {
console.log(result.toString());
})
Copy the code
With the callback, we can extract the getExt data.
Then, we solve the asynchronous problem with Node’s Events module:
// Introduce the fs modulelet fs = require("fs"); /** * Node event loop: * 1. Node is a single-process, single-threaded application, but supports concurrency through events and callbacks, so performance is very high. * 2. Each Node API is asynchronous and runs as a separate thread, using asynchronous function calls, and handling concurrency. Node has several built-in events. We can bind and listen for events by introducing the Events module and instantiating the EventEmitter class. */ // Introduce the Events modulelet events = require("events"); // Instantiate the event objectlet EventEmitter = new events.EventEmitter();
getExt = () => {
fs.readFile('08_ext.json', (err, data) => {// EventEmitter. Emit (emitter)'data', data.toString()); })}; getExt(); // Listen to data Eventemitter.on (emitter)'data', (ext) => {
console.log(ext);
});
Copy the code
In this case, EventEmitter. On gets the results of the execution inside the getExt in the form of listening data. So we know about Node’s I/O events and events module
3.10 the get and post
Returns the directory
No more words, first on the code:
index.js
Var HTTP = require();'http'); Var items = []; // Create the HTTP service http.createserver (function(req, res) {// set cross-domain domain name, * means allow any domain name cross-domain res.setheader ('Access-Control-Allow-Origin'.The '*'); // Set the header type res.setheader ('Access-Control-Allow-Headers'.'Content-Type'); Res.setheader ()'Content-Type'.'application/json'); // Switch (req.method) {// When a post request is made, the browser sends an options request first. If the request is passed, the browser continues to send a formal POST requestcase 'OPTIONS':
res.statusCode = 200;
res.end();
break; // If it is a GET request, return the items array directlycase 'GET':
let data = JSON.stringify(items);
res.write(data);
res.end();
break; // If it is a POST requestcase 'POST':
let item = ' '; Req.on (req.on);'data'.function(chunk) { item += chunk; }); Req.on (req.on)'end'.function() {// Save item = json.parse (item); items.push(item.item); // Return the data to the clientlet data = JSON.stringify(items);
res.write(data);
res.end();
});
break;
}
}).listen(3000)
console.log('http server is start... ');
Copy the code
First, we load the HTTP module and create the service. Then, we set up the cross-domain processing to allow for cross-domain. Next, we do the judgment processing of the request, which only determines whether it is a GET request or a POST request because we are doing a simple walkthrough. Finally, we return the result of the request to the client.
Above, we deployed the back-end Node, but what about the front-end page?
index.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
<meta http-equiv="X-ray ⌃ - Compatible" content="ie=edge">
<title>Node Web</title>
</head>
<body>
<div id="app">
<h1>Todo List</h1>
<ul>
<li v-for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
<input type="text" v-model="item">
<button @click="postApi"</button> </div> <! -- CDN reference: Vue and Node --> <script SRC ="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: document.getElementById('app'),
data: function () {
return {
items: [],
item: ' ',}},created() {// Go to the page and request data axios.get()'http://localhost:3000/').then(res => {
console.log("\n [api-get data]");
console.log(res);
this.items = res.data;
}).catch(function(err) {console.log(err)})}, methods: {// Click the button to submit the datapostApi() {
axios.post('http://localhost:3000/', {
item: this.item
}).then(res => {
console.log("\n [apI-post data]")
console.log(res);
this.items = res.data;
}).catch(function (err) {
console.log(err)
})
}
}
})
</script>
</body>
</html>
Copy the code
We did the layout through Vue and the interface request through Axios. Thus completes the operation to the data.
3.11 Node Connecting to MySQL
Returns the directory
For more information on MySQL installation, see Jsliang: MySQL Installation and Graphical Tools
First, we use visual tools to design the table:
The name | type | The length of the | key |
---|---|---|---|
id | int | 11 | A primary key |
name | varchar | 255 | |
age | varchar | 255 |
Then, we populate the table:
id | name | age |
---|---|---|
1 | jslliang | 23 |
2 | Liang Junrong | 23 |
Next, we install the Node connect MySQL package:
npm i mysql -D
Copy the code
Again, let’s write Node’s index.js:
index.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'node'
});
connection.connect();
connection.query('SELECT * FROM user'.function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
Copy the code
Finally, we open the service with node index.js:
[ RowDataPacket { id: 1, name: 'jsliang', age: '23' },
RowDataPacket { id: 2, name: 'Leung Jun-wing', age: '23'}]Copy the code
In this way, we have completed the Node connection to MySQL.
——————— Gorgeous dividing line ———————
Of course, add, delete, and check is the basic operation of the back end, so here we can complete the basic add, delete, and check function.
First look at the catalogue:
- Add new table fields
add.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456',
database: 'node'
});
connection.connect();
let addSql = "INSERT INTO user(id,name,age) VALUES(0,? ,?) ";
let addSqlParams = ["jsliang"."23"];
connection.query(addSql, addSqlParams, function (err, res) {
if (err) {
console.log("New error:");
console.log(err);
return;
} else {
console.log("Added successfully:"); console.log(res); }}); connection.end();Copy the code
To add data to the database, we simply need to node add.js directly.
- Delete table fields
delete.js
Var MySQL = require();'mysql'); Var connection = mysql.createConnection({host:'localhost',
user: 'root',
password: '123456',
database: 'node'}); // Start connection. Connection.connect (); Var delSql = var delSql ='DELETE FROM user where id = 2'; // Connect the SQL and execute the statement connection.query(delSql,function (err, res) {
if (err) {
console.log("Delete error:");
console.log(err);
return;
} else {
console.log("Deletion succeeded:"); console.log(res); }}); // Terminate the connection.end();Copy the code
- Modify table fields
update.js
Var MySQL = require();'mysql'); Var connection = mysql.createConnection({host:'localhost',
user: 'root',
password: '123456',
database: 'node'}); // Start connection. Connection.connect (); // New SQL statement and new field informationlet updateSql = "UPDATE user SET name = ? ,age = ? WHERE Id = ?";
let updateSqlParams = ["LiangJunrong"."23"1]; // Connect to SQL and execute the statement connection.query(updateSql, updateSqlParams,function (err, res) {
if (err) {
console.log("Modify error:");
console.log(err);
return;
} else {
console.log("Modified successfully:"); console.log(res); }}); // Terminate the connection.end();Copy the code
- Query table fields
read.js
Var MySQL = require();'mysql'); Var connection = mysql.createConnection({host:'localhost',
user: 'root',
password: '123456',
database: 'node'}); // Start connection. Connection.connect (); // New SQL statement and new field informationlet readSql = "SELECT * FROM user"; // Connect the SQL and execute the statement connection.query(readSql, function (err, res) {
if(err) throw err; console.log(res); }); // Terminate the connection.end();Copy the code
Above, we have broken through the barrier between Node and MySQL, and realized the addition, deletion, modification and examination of data.
Four Web combat – enterprise official website
Returns the directory
In the actual code, we many times will encounter some small things, such as: logo production, ICO production, icon selection and so on……
The following are some of jsliang’s usual encounters
- Logo production
- Ico production
- Icon to pick
In addition, since there is nothing to talk about in HTML and CSS, the prerequisite static page jsliang for this chapter is already written, and you can download it before you study:
- Static page code address for this article
4.1 Programming Environment
Returns the directory
First, let’s look at our front-end base code: addresses
As mentioned above, we only need to know about the FrontEndCode directory and the NodeWeb directory. The other directories are for the exercise in the above section.
Then, we do back-end functional analysis:
- Message board. When a user clicks on a message board, it is necessary to determine whether the user is logged in. If the user has not logged in, the login page is directly skipped. If the user is logged in, the message board page is displayed.
In the message board page, there are two interfaces:
- Obtaining message Content: obtaining
getMessage
Interface to return all message messages. As there is not much information, the paging function is not provided here. You can design the paging interface after you complete the function. - Submitting a Message: obtaining
sendMessage
Interface to send the user name, user ID, and message content to the back end.
- On the login page, there is an interface:
- The login: obtaining
login
Interface to submit the name and password entered by the user.
- In the registration page, there is an interface:
- registered: obtaining
register
Interface to submit the name and password entered by the user.
Therefore, we can design the interface combination of the front and back ends:
Interface documentation
interface | type | parameter | Return information |
---|---|---|---|
getMessage : Obtains message information |
get | No arguments | N records: ID (user ID), user_name(user name), user_message(user message content), and time(message time) |
sendMessage : Submit message |
post | User ID, user_name, user_message(user message content) | State of the status |
login Login: |
post | Id, user_name, user_password | State of the status |
register Register: |
post | Id, user_name, user_password | State of the status |
Finally, we carry out the design of MySQL database table:
The user table
The name | type | The length of the | key |
---|---|---|---|
id | int | 11 | A primary key |
user_name | varchar | 255 | |
user_password | varchar | 255 | |
time | datetime |
The message list
The name | type | The length of the | key |
---|---|---|---|
id | int | 11 | A primary key |
user_message | varchar | 255 | |
user_id | varchar | 255 | A foreign key |
user_name | varchar | 255 | |
time | datetime |
4.2 Back-end Ports
Returns the directory
Before we do this, we need to make sure that we can write the interface, so we can create a test folder and put an index. HTML and index.js in it.
- text
- index.html
- index.js
Copy the code
First, we set the back-end interface mentioned in 4.1 in advance:
index.js
NPM I MySQL -d var MySQL = require(NPM I MySQL -d var MySQL = require('mysql'); Var connection = mysql.createConnection({host:'localhost',
user: 'root',
password: '123456',
database: 'nodebase'}); // Start connection. Connection.connect (); // Introduce the HTTP module: HTTP is the foundation of providing Web services const HTTP = require("http"); Const url = require() const url = require() const url = require()"url"); // Introduce the QS module: qs is a path to json or json to string path const qs = require("querystring"); /** * req (request) * res (response) */ http.createserver ()function(req, res) {// set cors cross-domain res.setheader ("Access-Control-Allow-Origin"."*"); // Set the header type res.setheader ('Access-Control-Allow-Headers'.'Content-Type'); Res.setheader ()'Content-Type'.'application/json');
if (req.method == "POST") {// Interface POST form console.log("\n [POST form]"); // Obtain the routing address sent by the front endlet pathName = req.url;
console.log("\n interface:"+ pathName); // Receive the sent parameterlet tempResult = ""; // Req.addListener ("data".function(chunk) { tempResult += chunk; }); Req.addlistener ()"end".function () {
var result = JSON.stringify(qs.parse(tempResult));
console.log(The \n parameter is:");
console.log(result);
if (pathName == "/sendMessage") {// submit message console.log("\n [API - submit message]");
} else if (pathName == "/login") {// Log in to console.log("\n [API - login]");
} else if (pathName == "/register") {// register console.log("\n [API - registration]"); } // Interface information processing is complete}) // data receiving is complete}else if (req.method == "GET") {// interface GET form console.log("\n [GET form]"); // Parse the URL interfacelet pathName = url.parse(req.url).pathname;
console.log("\n interface:" + pathName);
if (pathName == "/getMessage") {// Get message console.log("\n [API - get message information]");
} else if(pathName == "/") {// home res.writehead (200, {"Content-Type": "text/html; charset=UTF-8"
});
res.write( < span style="text-align:center" style="text-align:center"> Node base < / a > < / h2 > '
); res.end(); } } }).listen(8888); // Get the current timefunction getNowFormatDate() { var date = new Date(); var year = date.getFullYear(); Var month = date.getmonth () + 1; Var strDate = date.getDate(); Var hour = date.gethours (); Var minute = date.getminutes (); Var second = date.getminutes (); / / SEC.if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0"+ strDate; } yyyY-MM-dd hh:mm:ss var currentDate = year +"-" + month + "-" + strDate + "" + hour + ":" + minute + ":" + second;
return currentdate;
}
Copy the code
Req. Method is a GET or a POST method to determine the interface to load:
- in
POST
The judgment is to belong toSubmitting a Message,The loginorregistered; - in
GET
In, judge whetherObtaining Message.
At the same time, we define the MySQL connection and a getNowFormatDate to get the current time in the format of 2018-12-21 10:03:59
We then demonstrate whether our interface works with a front page:
index.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = no">
<meta http-equiv="X-UA-Compatible" content="ie=edge"</title> </head> <body> <div> <labelfor="user"> Username </label><inputtype="text" id="user">
</div>
<div>
<label for="password"> close & have spent Code < / label > < inputtype="password" id="password">
</div>
<div>
<button id="register"</button> </div> <script SRC ="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
$(function() {// test get interface $.ajax({url:"http://localhost:8888/getMessage".type: "POST",
data: {
username: "jsliang"
},
success: function (res) {
console.log(res);
},
error: function(err) { console.log(err); }}) $("#register").click(function{// test the post interface $.ajax({url:"http://localhost:8888/login".type: "POST",
data: {
username: $("#user").val(),
password: $("#password").val()
},
success: function (res) {
console.log(res);
},
error: function(err) { console.log(err); }})})}); </script> </body> </html>Copy the code
Finally, we check our interface through the F12 console by node index.js and opening index. HTML:
You can see that our interface can be tuned properly, so that we can connect to the database, and carry out the design of these four interfaces.
If you find it difficult to restart Node index.js every time you update Node code, you can use supervisor to monitor changes in Node code. The supervisor is installed using: supervisor
4.3 Registration Function
Returns the directory
Good, let’s go back to the parody enterprise website page and get ready to write interfaces and enrich Node’s interfaces.
First, we start the front-end and Node services:
-
Open the command line/terminal
-
Open the front
cd FrontEndCode
live-server
Install live-server: NPM I live-server -g
- Open the back-end
cd NodeWeb
supervisor index.js
Install supervisor: NPM I supervisor -g
We then trigger the call interface by clicking on the event on the registration page:
register.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="keywords" content="Front-end, Jsliang, Bootstrap, enterprise site">
<meta http-equiv="description" content="Jsliang for you to create the best business services">
<link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Register - Jsliang Front-end Limited </title> <link rel="stylesheet" href="./css/index.css">
<link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <! <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC =". / js/jquery - 3.3.1. Min. Js. ""></script>
<script src="./js/bootstrap.min.js"></script>
<script src="./js/islogin.js"></script>
<script>
$(function() {$("#register-submit").click(function () {
let userName = $("#userName").val();
let userPassword = $("#userPassword").val();
if(! userName) { alert("Please enter your user name.");
$("#userName").focus();
} else if(! userPassword) { alert("Please enter your password");
$("#userPassword").focus();
} else if (userName.length > 10) {
alert("Please enter a user name with less than 10 characters.");
$("#userName").focus();
} else if (userPassword.length > 20) {
alert("Please enter a password of less than 20 characters");
$("#userPassword").focus();
} else{// If the user input is correct, then load the interface $.ajax({url:"http://localhost:8888/register".type: 'post',
dataType: 'json',
data: {
username: userName,
password: userPassword
},
success: function (res) {
console.log(res);
if (res.code == "0") {
alert("Successful registration, go to login!");
window.location.href = "./login.html";
}
},
error: function (err) {
console.log(err.responseText);
if (err.responseText == "Registration failed, duplicate name!") {
alert("User name has been registered!");
} else if (err.responseText == "Registration failed, quota full!") {
alert("Registration failed, quota full!");
} else if (err.responseText == "Registration failed, password is empty!") {
alert("Registration failed, password is empty!");
} else if (err.responseText == "Registration failed, name too long!") {
alert("Registration failed, name too long!");
} else if (err.responseText == "Registration failed, password is too long!") {
alert("Registration failed, password is too long!");
} else {
alert("Unknown error!");
}
}
})
}
})
})
</script>
</body>
</html>
Copy the code
So, when the user clicks the register button, we call the interface, send the data to the back end, and if it succeeds, it pops up and jumps to the login page; If it doesn’t work, it pops up.
Next, we write Node. After the front end calls the interface, Node determines whether the two parameters are empty, and if not, it stores the data in the database.
index.js
/ /... Other code is omitted. Please go to section 4.2 Back-end Interfaces to obtain other codeif (pathName == "/sendMessage") {// submit message console.log("\n [API - submit message]");
} else if (pathName == "/login") {// Log in to console.log("\n [API - login]");
} else if (pathName == "/register") {// register console.log("\n [API - registration]");
result = JSON.parse(result);
letusername = result.username; / / user nameletpassword = result.password; / / passwordlettime = getNowFormatDate(); / / timeif(! Username) {// The username is empty res.end("Registration failed, user name is null.");
return;
} else if(! Password) {// The password is empty res.end("Registration failed, password is empty!");
return;
} else if(username. Length > 10) {// name is too long res.end("Registration failed, name too long!");
return;
} else if(password.length > 20) {// The password is too long res.end("Registration failed, password is too long!");
return;
} else{// query the user table // The reason for using a Promise is because the database is called twice, and the database query is asynchronous, so you need to use a Promise. New Promise((resolve, reject) => {// New SQL statement and new field informationlet readSql = "SELECT * FROM user"; // Connect the SQL and execute the statement connection.query(readSql, function (error1, response1) {
if(error1) {// Throw error1 if the SQL statement is incorrect; }else {
console.log("\nSQL query result:"); // Remove the RowDataPacket and convert the result to a JSON objectletnewRes = JSON.parse(JSON.stringify(response1)); console.log(newRes); // Check whether the name is duplicatelet userNameRepeat = false;
for(let item in newRes) {
if(newRes[item].user_name == username) {
userNameRepeat = true; }} // If the name is repeatedif(userNameRepeat) {
res.end("Registration failed, duplicate name!");
return;
} else if(newres.length > 300) {// If the number of registrations is full res.end("Registration failed, quota full!");
return;
} else{// you can register resolve(); }}}); }).then( () => { console.log("\n Step 2:"); // New SQL statement and new field informationlet addSql = "INSERT INTO user(user_name,user_password, time) VALUES(? ,? ,?) ";
letaddSqlParams = [result.username, result.password, time]; // Connect the SQL and execute the statement connection.query(addSql, addSqlParams,function (error2, response2) {
if(error2) {// If the SQL statement is incorrect console.log("New error:");
console.log(error2);
return;
} else {
console.log("\nSQL query result:");
console.log(response2);
console.log("\n Registered successfully!"); Res.write (json.stringify ({code:"0",
message: "Registration successful!"})); Res.end (); }}); }) // Promise is finished} // Registration process is finished}Copy the code
Finally, let’s check to see if this feature is successful:
4.4 Login Function
Returns the directory
On top of that, we’ve completed the registration function, so the login function is relatively easy because we’ve already tried the query part once.
login.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="keywords" content="Front-end, Jsliang, Bootstrap, enterprise site">
<meta http-equiv="description" content="Jsliang for you to create the best business services">
<link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Login - Jsliang Front-end Limited </title> <link rel="stylesheet" href="./css/index.css">
<link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <! <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC =". / js/jquery - 3.3.1. Min. Js. ""></script>
<script src="./js/bootstrap.min.js"></script>
<script src="./js/islogin.js"></script>
<script>
$(function() {$("#login-submit").click(function () {
let userName = $("#userName").val(); / / user namelet userPassword = $("#userPassword").val(); / / passwordif(! userName) { alert("Please enter your user name.");
$("#userName").focus();
} else if(! userPassword) { alert("Please enter your password");
$("#userPassword").focus();
} else if (userName.length > 10) {
alert("Please enter a user name with less than 10 characters.");
$("#userName").focus();
} else if (userPassword.length > 20) {
alert("Please enter a password of less than 20 characters");
$("#userPassword").focus();
} else {
$.ajax({
url: "http://localhost:8888/login".type: 'post',
dataType: 'json',
data: {
username: userName,
password: userPassword
},
success: function (res) {
console.log(res);
if (res.code == "0") {
sessionStorage.setItem("id", res.data.id);
sessionStorage.setItem("userName", res.data.userName);
alert("Login successful!");
window.location.href = "./messageBoard.html";
} else if (res.code == "1") {
alert("Login failed, password error!");
}
},
error: function (err) {
console.log(err.responseText);
if (err.responseText == "User does not exist!") {
alert("User does not exist!");
} else if (err.responseText == "Login failed, user name blank!") {
alert("Login failed, user name blank!");
} else if (err.responseText == "Login failed, password blank!") {
alert("Login failed, password blank!");
} else if (err.responseText == "Login failed, name too long!") {
alert("Login failed, name too long!");
} else if (err.responseText == "Login failed, password too long!") {
alert("Login failed, password too long!");
} else {
alert("Unknown error!");
}
}
})
}
})
})
</script>
</body>
</html>
Copy the code
After writing the front-end code, we edit the Node code:
index.js
/ /... Other code is omitted. Please go to section 4.2 Back-end Interfaces to obtain other codeif (pathName == "/sendMessage") {// submit message console.log("\n [API - submit message]");
} else if (pathName == "/login") {// Log in to console.log("\n [API - login]");
result = JSON.parse(result);
letusername = result.username; / / user nameletpassword = result.password; / / passwordif(! Username) {// The username is empty res.end("Login failed, user name blank!");
return;
} else if(! Password) {// The password is empty res.end("Login failed, password blank!");
return;
} else if(username.length > 10) {
res.end("Login failed, name too long!");
return;
} else if(password.length > 20) {
res.end("Login failed, password too long!");
return;
} else{// New SQL statement and new field informationlet readSql = "SELECT * FROM user WHERE user_name = '" + username + "'"; // Connect the SQL and execute the statement connection.query(readSql, function (error1, response1) {
if (error1) {
throw error1;
} else {
if(response1 = = undefined | | response1. Length = = 0) {/ / there is no user res. End ("\n User does not exist!");
return;
} else{// there is a user console.log("\n User exists!");
let newRes = JSON.parse(JSON.stringify(response1));
console.log(newRes);
ifNewRes [0].user_password == password) {res.write(json.ify ({code:"0",
message: "Login successful!",
data: {
id: newRes[0].id,
userName: newRes[0].user_name
}
}));
res.end();
} elseRes.write (json.ify ({code:"1",
message: "Login failed, password error!"})); res.end(); } // Check whether the password is correct or not} // User processing is finished}}); } // End of login step}else if (pathName == "/register") {// register console.log("\n [API - registration]");
}
Copy the code
Good, the front end and back end are written, it’s time to check if the functionality is implemented:
4.5 Message Leaving
Returns the directory
Now, all we have left is the message function, so let’s work on it!
messageBoard.html
<! --> <! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="keywords" content="Front-end, Jsliang, Bootstrap, enterprise site">
<meta http-equiv="description" content="Jsliang for you to create the best business services">
<link rel="shortcut icon" href="./images/favicon.ico" type="image/x-icon" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; white-space: inherit! Important;"stylesheet" href="./css/index.css">
<link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <! <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC = <script SRC =". / js/jquery - 3.3.1. Min. Js. ""></script>
<script src="./js/bootstrap.min.js"></script>
<script src="./js/islogin.js"></script>
<script>
$(function() {
let userName = sessionStorage.getItem("userName");
let userId = sessionStorage.getItem("id"); // Check the message boardif(userName && userId) {// if there is stored $. Ajax ({url:"http://localhost:8888/getMessage".type: 'get',
dataType: 'json',
success: function (res) {
console.log(res);
let li = ``;
for(let item in res.data) {
li = li + `
<li>
<span class="text-warning font-bold"> do < / span > < span class ="user-message">${res.data[item].user_message}<span style = "box-sizing: border-box! Important; word-wrap: break-word! Important;"user-name">${res.data[item].user_name} [${res.data[item].user_id}]</span>
<span class="message-time">${res.data[item].time}</span>
</li>
`;
}
$("#message-board-ul").append(li);
},
error: function(err) { console.log(err); }})}else{// if window.location.href = is not stored".. /login.html"; } $($())"#message-submit").click(function() {
let messageText = $("#message").val()
if(! messageText) { alert("The message cannot be empty.");
} else if(messageText.length > 140) {
alert("Message length cannot exceed 140 characters!");
} else {
$.ajax({
url: "http://localhost:8888/sendMessage".type: 'post',
dataType: 'json',
data: {
userid: userId,
username: userName,
message: messageText
},
success: function (res) {
console.log(res);
if(res.code == "0") {
alert("Added successfully!");
window.location.reload();
}
},
error: function (err) {
console.log(err);
console.log(err.responseText);
if (err.responseText == "Login failed, message is empty!") {
alert("Login failed, message is empty!");
} else if (err.responseText == "Login failed, word limit exceeded!") {
alert("Login failed, word limit exceeded!");
} else {
alert("Unknown error!");
}
}
})
}
})
})
</script>
</body>
</html>
Copy the code
Next, write the Node backend:
index.js
/ /... Other code is omitted. Please go to section 4.2 Back-end Interfaces to obtain other codeif (pathName == "/sendMessage") {// submit message console.log("\n [API - submit message]");
result = JSON.parse(result);
let id = result.userid; // id
letuserName = result.username; / / user nameletmessageText = result.message; // Message contentlettime = getNowFormatDate(); / / timeif(! messageText) { res.end("Login failed, message is empty!");
return;
} else if(messageText.length > 140) {
res.end("Login failed, word limit exceeded!");
return;
} else{// New SQL statement and new field informationlet addSql = "INSERT INTO message(user_message, user_id, user_name, time) VALUES(? ,? ,? ,?) ";
letaddSqlParams = [messageText, id, userName, time]; // Connect the SQL and execute the statement connection.query(addSql, addSqlParams,function (error1, response1) {
if(error1) {// Throw error1 if the SQL statement is incorrect; }else {
console.log("\n New success!"); Res.write (json.stringify ({code:"0",
message: "Added successfully!"})); Res.end (); }}}})else if (pathName == "/login") {// Log in to console.log("\n [API - login]");
} else if (pathName == "/register") {// register console.log("\n [API - registration]"); } / /... Other code is omitted. Please go to section 4.2 Back-end Interfaces to obtain other codeif (pathName == "/getMessage") {// Get message console.log("\n [API - get message information]"); // Parse the URL parameter sectionlet params = url.parse(req.url, true).query;
console.log(The \n parameter is:"); console.log(params); // New SQL statement and new field informationlet readSql = "SELECT * FROM message"; // Connect the SQL and execute the statement connection.query(readSql, function (error1, response1) {
if (error1) {
throw error1;
} else {
letnewRes = JSON.parse(JSON.stringify(response1)); console.log(newRes); Res.write (json.stringify ({code:"1",
message: "Query succeeded!", data: newRes })); Res.end (); }}); // Query finished}else if(pathName == "/") {// home res.writehead (200, {"Content-Type": "text/html; charset=UTF-8"
});
res.write( < span style="text-align:center" style="text-align:center"> Node base < / a > < / h2 > '
);
res.end();
}
Copy the code
Knock out the code and see if the function is implemented:
To sum up, we have completed all the functional modules: registration, login and message leaving.
Integration of five tools
Returns the directory
He that would do a good job must sharpen his tools. With tools in your hands, you can develop faster.
5.1 Supervisor – Listens for Node changes
Returns the directory
- The supervisor’s official website
As its website says, it is an operational control system:
- Install plug-in:
npm i supervisor -g
- Run file:
supervisor app.js
- View run:
localhost:3000
When we modify the contents of app.js after node app.js, we need to close the node command line before executing node app.js. After we use supervisor, we modify the content in app.js. As long as you click “Save”, the saved code will take effect, realizing real-time monitoring of changes in Node code.
More details about this tool are available online:
- Detailed version: with the Supervisor to protect your Node. Js process | Jane books – Mike’s reading season
5.2 Pm2-node Process Management
Returns the directory
- PM2 – npm
PM2 is a Node process management tool that can simplify the cumbersome tasks of managing many Node applications, such as performance monitoring, automatic restart, and load balancing, and is very simple to use.
The following is an introduction to PM2, which basically covers the common functions and configurations of PM2:
- Install PM2 globally:
npm i pm2 -g
- Listening for applications:
pm2 start index.js
- View all processes:
pm2 list
- To view a process:
pm2 describe App name/id
- Stop a process:
pm2 stop App name/id
. Such as:
Pm2 list:
App name | id | status |
---|---|---|
index | 0 | online |
Run the pm2 stop index or pm2 stop 0 command.
- Stop all processes:
pm2 stop all
- Restart a process:
pm2 restart App name/id
- Delete a process:
pm2 delete App name/id
As mentioned above, if our supervisor is listening to a single process, then PM2 is listening to multiple processes.
More tips:
- PM2 website
- Introduction | Jane books – LeavesLife PM2 usage
- PM2 practical guide | blog garden – apes small card program
6 reference Materials
Returns the directory
In the process of writing this article, a few references are worth keeping in mind:
- Classic: this class is worth reading
Classic, it is as time goes by, it still has reference value.
- The API documentation | Node. Js Chinese website
- Node. Js tutorial | novice tutorial
- | Express Chinese Express document
- Try: This class is worth our reference
Node Basic Module
- The querystring of nodejs module garden – whiteMu | blog
Write interfaces for Node
- Written in the Node RESTful API interface | PHP Chinese – don’t speak
MySQL learning
- MySQL tutorial | novice tutorial
Node Connecting to database
- Node. Js sample — Taiwan before and after interaction using node. Js, realize the function of user registration | blog garden – return to the home page The party xing Ming
- Node.js implements a simple login registration page – Blog Garden – return to the home page Bestjarvan
The Node imitation Express
- Nodejs module: simple HTTP request routing, copy express | CSDN – TTUZ
- A beginner nodejs: don’t get dizzy with the Express API | front-end stew – flying little black pig god
- NodeJs combat – native NodeJs light imitation Express framework from requirements to achieve (a) | stubborn stone – the nuggets
- NodeJs combat – native NodeJs light imitation Express framework from requirements to achieve (2) | stubborn stone – the nuggets
- Imitation Express | making – wallaceyuan
- Node. Js encapsulation imitates the express routing | CSDN – c.
- Learning node express middleware framework of knowledge and practice in | making – BadWaka
Seven-line deployment
Returns the directory
For online deployment and configuration related to domain names and servers, Jsliang covers this in another post: Cloud Server building.
If you need to order a cloud server to store static or Node back-end web pages like Jsliang personal website, but you don’t know how to choose, you can add jsliang QQ: 1741020489, here are some discount promotion:
Tencent Cloud promotion:
New users click here:
- New customer no threshold of 2,775 yuan voucher
Buy a cloud server:
- December discount as low as 168 yuan/year
Ali Cloud promotion:
New users click here:
- New user Cloud product 1888 Universal Voucher
Buy a cloud server:
- High performance cloud server – as low as 293 YUAN/year
Purchase an enterprise-class cloud server:
- Enterprise-level high-performance cloud server
Viii Induction and Summary
Returns the directory
So, all done! Perhaps under the destruction of the previous code, can see here is very few friends, but I firmly believe that I should explain the basic explanation, should not explain also explained ~ so, if the friends really feel good after reading, then a thumbs up or give a star! Your likes and stars are the motivation for me to write more and more wonderful articles! Making the address
If you want to comment on this, you can add a code word: Node base, ***
- Node Basics, I’m done!
- I want to say jsliang must be lazy, not perfect, I don’t care if I pay you to improve me!
- …
So, that ‘s all, thanks ~
———————–
Afterword.
Writing is not easy, if the article is helpful to small partners, I hope that small partners to hard knock code, hard to write Jsliang wechat/Alipay reward, your every reward is the best encouragement, thank you ~
jsliangThe document library 由 Liang JunrongusingCreative Commons Attribution – Non-commercial – Share in the same way 4.0 International licenseLicense.
Based on theLot. Om/LiangJunron…On the creation of works.
Permissions outside of this license agreement may be obtained fromCreativecommons.org/licenses/by…Obtained.