The origin of Node.js
Originated by Ryan Dahl (Russian)
Website development (web page production) since 2006
2009 was the first year of Node
What is Node.js?
Is a development platform that lets JavaScript run on the server side, based on the V8 engine. It extends JavaScript’s reach to the server side, putting it on a par with PHP, JSP, Python, Ruby, and ASP.
Node.js has no external container, no other configuration or language support to run, and Node has no fixed folder.
How is Node.js different from other background languages?
1. Node is single-threaded, while others are multi-threaded
2. The concept of a Web container is static
For example, wampServer supports WWW, Apache, PHP, mysql, etc., which is required to run HTML files, while Node can run HTML files anywhere as long as the path is correct
4. Advantages and disadvantages of Node.js
Advantages: small size, high concurrency, superior performance
Cons: Not suitable for large projects
5. Features of Node.js
Single thread: Saving memory overhead, low cost, high concurrency (single thread? Only one process can be started at a time. The next process can be started only after the current process is completed. The current process breaks down and the server crashes.
Non-blocking I/O: Execute efficiently, take full advantage of CPU performance, and use callback functions to execute logic code to reflect event loops. (Non-blocking I/O? Accessing the event loop based on the callback function)
Event-driven: The ability to handle a series of cyclic events in a callback function after an event is triggered, also known as an “event loop” mechanism.
Application scenarios of Node
Live communication with webSocket: user form collection, exam system, live chat, live graphics, JSON API (for foreground Angular)
Node, NPM (package management tool), Express (plugins in Node for routing)
Parse (), json.stringify (), eval(
Json.parse () : Converts JSON strings into JSON objects.
Json.stringify () : Converts a JSON object to a JSON string.
Eval () : Evaluates a string and executes a javascript expression or statement within it.
HTTP module in Node
Var HTTP =require(” HTTP “);
Var server= http.createserver (function(req,res){})
Where REq is short for request (which can be routed) res is short for response
Listen (3000,”127.0.0.1″) localhost to suspend the server
4. Set the HTML encoding format of the request header 200 status code
res.writeHead(200,{“Content-type”:”text/html; charse=utf-8″});
5. The response is complete and data is displayed on the page
res.end((1+2+3+4+5).toString()); // The response ends otherwise it will keep loading
6. Req. url is the path after the domain name in the address bar:
The default returns: /favicon.ico and /
Returns: / red/green/orange? name=”xx”&age=123
7. Add content to web page (can parse tags) equivalent to document.write() in JS
Res. Write (” < / h1 > < h1 > content “);
8. To view the contents of the passed parameters, use the following command:
console.log(arguments); // Output all methods of req and res
9. Go to the last or last path in the path
1) the req. Params [0] / / localhost: 3000 / the teacher / 123456 output of 123456
/Children/:id var id=req.params[“id”];
The FS module reads the resource template
Var fs=require(“fs”)
Fs.readfile (“./green.html”,function(err,data){})
Fs.writefile (“./2. TXT “,data,function(err){})
Fs.copyfilesync (“1.txt”,”4.txt”,function(err){}); (pending)
5. Read the folder: fs. Readdir (“. / sys/”, function (err, files) {});
6. Check if it is a folder:
for(leti=0; i<files.length; Stat ("./sys/"+files[I],function(err,stats){if(stats.isdirectory ()){fs.stat("./sys/"+files[I],function(err,stats){if(stats.isdirectory ()){ arr.push(files[i]) } console.log(arr) }); If (fs.lstatsync ("./sys/"+files[I]).isDirectory()){arr1.push(files[I]); } console.log(arr1); }Copy the code
7. Create file directory makdir
Url module in Node
Var url=require(“url”);
2. Obtain the following part of the URL path: var pathName =url.parse(req.url).pathname
For example: the location bar / / http://127.0.0.1:4000/aaa/bbb? name=”xx”22&age=20
The obtained value is /aaa/ BBB
Pathname.indexof (“.”)==-1 // Returns whether a point exists in the pathName path, -1 indicating that it does not
3. Match search (?) Parse (req.url,true).query;
For example: the location bar / / http://127.0.0.1:4000/aaa/bbb? name=”xx”22&age=20
{name: ‘”xx”22′, age: ’20’} if true, display it as an object
4. Url.parse (req.url).path (Retrieve all fields except port)
Obtain: /teacher/123456? name=%22xx%22&&age=12
11. Path module in Node
Var path=require(“path”); // Load the path module
2. Return the extension in the path: path.extName (url.parse(req.url).pathname)
If path ends in a ‘.’, it returns a ‘.’, if there is no extension and it does not end in a ‘.’, it returns a null value.
3. Normalize the given path and parse ‘.. ‘and ‘.’ fragments: path.normalize(req.url)
For example: the path. The normalize (‘ C: / / / / temp \ \ \ \ / \ \ / \ \ / foo/bar ‘);
// Returns: ‘C:\\temp\\foo\\bar’
Xii. Modules
Two ways of exposing modules and their differences
Exports exposes module module. Exports exposes an object distinction: Module. exports starts with an empty object {} that can only appear once for a class (constructor). Exports refers to modules Module: exports: exports. MSG = exports; // MSG is an exports.show=show; //show is a function of module.exports: module.exports={MSG: MSG, // MSG is a variable of show:show //show is a function of} module.exports=People; //People is a constructorCopy the code
Package management tools
NPM (foreign, more comprehensive, slow download speed) and CNPM (domestic, Taobao mirror, fast download speed, defective)
NPM –registry registry.npm.taobao.org install
NPM package management tools:
What it does: Downloads plug-ins, libraries, and frameworks while updating package versions
NPM install library name plug-in name framework name -g(global)
The node_modules folder will be automatically downloaded and deleted when copying the project, then NPM install will install the project dependencies
Querystring module
Querystring =require(” queryString “) // Query the specified string
2. Deserialize a string into an object: queryString.parse (STR,separator,eq,options)
Parameter: STR specifies the string to be deserialized; Separator refers to the character or string used to separate the string STR. The separator defaults to "&"; Eq (sparing) refers to the character or string used to divide keys and values. The default value is "="; MaxKeys: pass in a number to specify the maximum number of key/value pairs to parse. The default value is 1000. If set to 0, cancel the limit on the number of pairs to parse. DecodeURIComponent: Pass a function to decode strings containing %, default queryString.unescape.Copy the code
15. Template for uploading pictures
var http=require(“http”); // Introduce the HTTP module
var formidable=require(“formidable”); // Import file upload module with NPM download
var util=require(“util”); / / tool library
var fs=require(“fs”);
var path=require(“path”);
var sd=require(“silly-datetime”); // Download the time module with NPM
Format (new Date(),’YYYYMMDD’)//
Use NPM command to download (JADE) template engine
1. What is EJS?
EJS is a simple and efficient templating language that generates HTML markup text from data and templates. EJS can be said to be a JavaScript library, EJS can run on the client side and the server side, the client installation directly into the file, the server side with NPM package installationCopy the code
2.EJS features:
Quick compilation and rendering of simple template tags custom tags delimiter support text inclusion support for browser-side and server-side templates static cache support for Express view systemCopy the code
EJS member functions:
Render (STR,data,[option]): directly render the string and generate HTML STR: string template to parse data: data: configuration optionsCopy the code
4.EJS common labels
<% %> Process control tag <%= %> Output tag (original output HTML tag) <%- %> Output tag (HTML will be parsed by the browser) <%# %> Comment tag % Escape tags -%> Remove useless Spaces description: EJS logic code all use JavaScriptCopy the code
Xvii express module uses NPM command to download mainly for routing
1. Concept: Express is currently the most popular Web development framework based on Node.js, which can quickly build a fully functional website. Var express=require("express") var express=require("express"); var app=express(); App.use (express.static("./views")); 3. Koa is the next generation of Web development frameworks based on Node.js, smaller, more expressive, and more robust Web frameworks. Generator functions can avoid repetitive and verbose nested callback functions 4. Middleware body-parser 5. Cookie-parser 6. Express-session 7. Cookie-session 8Copy the code