About Node

1) the concept of the NODE

A tool or environment that renders JS based on the V8 engine (Google’s Browser engine)

  • Install Node (download it from http://nodejs.cn/)
  • Execute the JS code in the Node environment

2) After NODE is installed

  • After the current computer is installed automaticallyNPM (node Package Managernode module manager): a js module (all packaged for other people to access the use of called modules or packages) management tool, based on NPM can be installed and downloaded JS modules
  • It generates commands that Node executes (either in a DOS window or a terminal command) :node xxx.js

3) How to render and parse JS in NODE

  • REPL mode:Read-Evaluate-Print-LoopInput-evaluation-output-loop
  • Execute JS files directly based on Node
    • Execute in a command window (DOS window & Terminal window)

Most people call Node a background programming language because:

  • 1) We can install Node on the server
  • 2) We can write JS code on the server, through Node (we can use JS to operate the server, in other words, use JS to achieve some functional operations on the server side)

4) Advantages and features of NODE:

Traditional background language: JAVA/Python/PHP/C#

  • Single thread
  • V8 based rendering: Fast
  • Asynchronous non-blocking I/O operations: I=> INPUT O=>ouput Reads and writes to files
  • Event-driven: Similar to publish-subscribe or callback functions
  • JS runs in the client browser => front end
    • Browsers provide many global properties and methods to JSwindow.setTimeout...
  • JS running in server-side node => background
    • NODE also provides a number of built-in properties and methods for JS:http/fs/url/path...Object, etc., provide many apis for JS operations
  • The front end (the browser running JS) limits I/O operations
    • input type='file'This is an I/O operation, but requires manual selection (and only reads, not writes)
  • The back-end (js running in node) does not limit I/O operations

5) Modules in Node

Node itself is based on the commonJS module specification design, so modular node composition

  • Built-in module: Node provides natural JS access to use
  • Third party modules: written by others, we can install and use based on NPM
  • Custom modules: modules created by yourself

CommonJS specification

(AMD/CMD/ES6 MOUDLE are modular design ideas)

  • CommonJS specifies that each JS is a separate module. (Modules are private: values, variables, and functions are private and do not conflict with the contents of other JS files.)
  • CommonJS allows methods in modules to call each other
    • Module B wants to call the method in module A
    • = > export A
    • B = > import

1) derived

CommonJS sets built-in variables/properties/methods in every module (every JS)

  • module: represents the current module object.
  • module.exports: this of the moduleattributeIs the [object] used to export property methods
  • exportsThe: is a built-in variable that is also used to export the current module property methods, although andmodule.exportsNot a thing, but the corresponding value is a (module.exports=exportsValues are objects)

2) import

  • requireCommonJS: a built-in variable used to import modulesmoudle.exportsSomething exposed)
    • The imported value is object

3) require import:

  • First turn on theabout_node.jsThe code in the module executes from top to bottom, importing exports of memory, so the accepted result is an object
  • requireIs aSynchronous operationGet the value only after executing the imported module code, and then continue executing the code below this module
  • let temp1 = require('./about_node');/ / = >. /Is specifically to specify a module in the current directory (.jsCan be omitted)

4) require import rules:

  • require('./xxx')or../xxxor/xxx

In other words, if you want to import a custom module, you must add a path

  • require('./xxx')

Node_modules = node_modules = node_modules = node_modules = node_modules = node_modules

5) CommonJS features:

  • All code runs in the module scope and does not contaminate the global scope. (Each module is private, and everything in it is private and does not interfere with other modules.)
  • Modules can be loaded multiple times, but only run once on the first time they are loaded. The results are then cached and read directly after being loaded. In order for the module to run again, the cache must be cleared (to reduce the number of times the module code is repeated).
  • The CommonJS specification loads modules synchronously in the order in which they appear in the code

The built-in variable __dirname & __filename

  • __dirnameThe built-in variable in the module is the absolute path of the current module (specific to drive letter: physical path)
    • console.log(__dirname)
    • C:\Users\lenovo\Desktop\notes\NODE
  • __filename: more module names (i.e. file names) than _dirname
    • C:\Users\lenovo\Desktop\notes\NODE\about_node.js

The sample

// about_node.js
let a = 12;
let fn = b= > {
    return a * b
}
// console.log(1)
// setTimeout(()=>{
/ / the console. The log (1.5)
/ /}, 1000)
exports.fn = fn; // Put the current module's private functions in the exports object (assigned to one of its properties), so that other modules can use <=> moudle.exports.fn = fn based on the require import
// console.log(2)

console.log(__dirname); //C:\Users\lenovo\Desktop\notes\NODE
console.log(__filename) //C:\Users\lenovo\Desktop\notes\NODE\about_node.js
Copy the code
// about_node2.js
let a = 2;
let fn = b= > {
    return a / b
}
let temp1 = require('./about_node'); //./ specifies a module in the current directory (.js can be omitted).
// console.log(3); Run the about_node.js code first and then run the about_node2.js code
// // If add timer 1 2 3 1.5
// console.log(temp1); // now temp1 is an object {fn:... }
console.log(temp1.fn(10)); //120 uses about_node.js variables A and fn

// // does not execute about_node.js the second time because the first time the exported result is cached but rarely written twice
// temp1 = require('./about_node');
// console.log(temp1.fn(10)); / / 120
Copy the code

4. Fs built-in module

[Built-in module FS: I/O operation]

Common methods:

  • fs.mkdir / fs.mkdirSyncSync is used to create folders synchronously and asynchronously. To achieve non-blocking I/O operations, we usually use asynchronyfs.mkdir(path,callback) fs.mkdirSync(path)`
  • fs.readsir / fs.readdirSync: Reads the contents of a file directory
  • fs.rmdir / fs.rmdirSync: Delete folder (if folder has content cannot be deleted)
  • fs.readFile: Reads the contents of the file
  • fs.writeFile: Write to a file (overwrite write: write new content to replace the original content)
  • fs.appendFile: Appends new content, the original content is still in
  • fs.copyFile: Copies the file to a new location
  • fs.unlink: Delete files
let fs = require('fs');

// Create folder synchronization will cause blocking, generally use asynchronous
fs.mkdir('./less',(err)=>{
    if(err){
        console.log(err);
        return;
    }
    console.log('ok');
});
console.log(1);

// Read file directory asynchronously
fs.readdir('/',(err,result)=>{
    if(err) {,// console.log(err);
        return;
    };
    console.log(result); // The current file directory ['less', 'module_fs.js'] returns an array
});

// Delete the folder (the folder must be empty)
fs.rmdir('./less',err=>{
    if(err){
        console.log(err);
        return;
    }
    console.log('ok');
})
{[Error: ENOTEMPTY: directory not empty, rmdir 'C:\Users\lenovo\Desktop\notes\NODE\module_fs\less'] */

// Read the contents of the file
fs.readFile('./less/less.js'.'utf-8',(err,result)=>{
    if(err){
        // console.log(err);
        return;
    }
    console.log(result);// File contents (string format) setTimeout(()=>{console.log(123)},1000)
    // Do not set utF-8 encoding format, read the data in buffer format, after setting string data
})

// Write to file (overwrite write)
fs.writeFile('./less/less.js'.'ha ha'.'utf-8',(err)=>{
    // The second argument is that what is written to the file overwrites the original content
})

// Write to file (append write)
fs.appendFile('./less/less.js'.'hey'.'utf-8',(err)=>{
    // The second argument is to append the content written to the file to the original content
})

// Delete files
fs.unlink('./less/less.js',(err)=>{
    if(err){
        return;
    }
    console.log('ok')})Copy the code

5. Url built-in module

[URL built-in module]

url.parse(url[,flag]):

  • A URL address is parsed and each part of the address is stored as an object key-value pair
  • The second argument defaults to false, and is set to true to parse the part of the question mark as an object key-value pair
    • Query: [Object: null prototype] {from: ‘qq’, lx: ‘stu’},

Url {

  • Protocol :’ HTTP :’, //=> protocol
  • Slashes: true, //=> Whether there is a double slash
  • auth: null, //=>
  • Host: ‘baidu.com’, //=> Domain name + port number
  • Port: null, //=> port
  • Hostname: ‘baidu.com’, //=> domain name
  • Hash: ‘#video’, //=> hash value
  • search: ‘? From =qq&lx=stu’, //=>
  • Query: ‘from=qq&lx=stu’, //=> question mark Parameter [string] contains no question mark
  • Pathname: ‘/’, //=> pathname of the requested resource
  • path: ‘/? from=qq&lx=stu’, //=>pathname + search
  • Href: ‘baidu.com/?from=qq&lx… ‘//=> url}
let url = require('url');
console.log(url.parse('http://baidu.com?from=qq&lx=stu#video'.true));
// Return a URL object
Copy the code

HTTP built-in modules

[HTTP built-in module]

Server-side task

  • 1. Create service (web server with specified port)
  • 2. Receive the request information from the client, parse it, obtain the required content, and send the response to the client

Note: To create a daemon based on Node, we usually create a server module, which implements the creation of web services and the processing of requests (usually put the Server module in the current project root directory).

// Import the built-in module
let http = require('http');
let url = require('url');
let path = require('path');
let fs = require('fs');

// Create a Web service
let port = 80;
let server = http.createServer((req,res) = >{
    /* The callback function is executed only when the service is successfully created and the client sends a request to the current service. If the request is sent once, the callback function is triggered once. Corresponding to a good protocol, domain name, port and other information, in the browser or Ajax, etc. Send a request can http://localhost:80/... Localhost Indicates the domain name of the local computer, that is, the client server of the local computer, and access the server programs of the local computer (that is, the PC is both the client and the server). If the IP address is an Intranet IP address, users on the same LAN can access the service. If the IP address is an external IP address, all users connected to the Internet can access the service. (If the IP address is an Intranet IP address, you need to disable the firewall.) In CMD, enter ipconfig => 172.18.0.80 localhost:80/, which is the same as 172.18.0.80:80/ */ 
    console.log('hello world! ');
});

server.listen(port,()=>{
    // Callback function: the callback function that is triggered when the service has been successfully created and the port number has been listened on
    console.log(`server is success,listen${port}! `); // server is success,listen80!
});// Listen on a port [0 to 65535]
//http.createServer().linten(80);

// When the service is successfully created, the cursor blinks on the command line, indicating that the server is running. CTRL + C => Stop running the service

Copy the code

1) About parameters REq and RES

Two parameters

    1. req:requireRequest object that contains the client’s request information (excluding hash values)
    • req.urlStores the path address of the requested resource and the question mark parameter
    • req.methodClient request mode
    • req.headersClient request header information (is an object)
    1. res:responseThe response object contains properties and methods that allow the server to return content to the client
    • res.writeBased on this method, the server can return content to the client
    • res.endEnd response –res.writeHeadOverride response header information (which is an object)
      res.writeHead(200, {'content-Type':'text/plain; charset=utf-8'
          // text/plain The plain text type
      })
      Copy the code
    • res.setHeaderOverwrite the response header (without writing the status code)res.setHeader('Content-type','text/html; charset=utf-8');

2) About req.url: resolve the path name and question mark parameter in the REQUESTED URL address respectively

Parse url.parse(req.url)

// Parse the path address in the URL and the question mark parameter separately
let {pathname,query} = url.parse(req.url,true)
console.log(pathname,query);
/* /index.html [Object: null prototype] { uesr: 'tom', name: 'haha' } */
Copy the code
let http = require('http');
let url = require('url');
let path = require('path');
let fs = require('fs');

// Create a Web service
let port = 8080;
// let handle = function handle(req,res){
    
// }
// http.createServer(handle).listen(port);

let server = http.createServer((req,res) = >{
    // console.log(url,method,headers);
    // // Gets specific information in the request header
    // console.log(headers['user-agent']);
    / * /? User = Tom GET header: {host: 'localhost:8080', connection: 'keep-alive', 'upset-insecure -requests': '1', 'user-agent': 'the Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36', Accept: 'text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp image/apng,; Q = 0.8, application/signed - exchange; v=b3', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh; Q = 0.9 '} * /

    // res.write('hello world! ');
    // res.end('hello world! '); // Indicates that the server returns the contents of a string and terminates the response

    // The override response header is an object.
    /* The object has two arguments: 1. HTTP status code 2.' Content-type ':'text/plain; Charset =utf-8'
    res.writeHead(200, {'content-Type':'text/plain; charset=utf-8'
       // text/plain The plain text type
    })
    res.end(JSON.stringify({name:'Hahaha'}));//{"name":" XXX "} Returns a string in JSON format
    
});
server.listen(port);

Copy the code

7. About NPM

  • npm -vView the NOM version number
  • npm installThe installation
  • npm init -yConfiguration Item List
    • Will automatically generatepackage.jsonfile
/ / package. Json file
{
    "name": "NODE"."version": "1.0.0"."description": ""."main": "server.js"."scripts": {
        "server": "node server.js"
    },
    "keywords": []."author": ""."license": "ISC"
}
Copy the code

Get write request interface


<input type="text" id="txt" />

Copy the code
txt.onblur = function () {
    jsonp({
        callback:'cb'.url:"http://localhost".data: {user:this.value
        },
        success:function(data){
            console.log(data); }})}function jsonp(json) {
    let opt = {
        callback: 'callback'.url: ' '.data: {},}let fnName = json.fname || 'jQuery_' + (Date.now());
    window[fnName] = function (data) {
        json.success(data);
        // delete window[fnName];
        window[fnName] = null;
    }

    // Dynamic creation is asynchronous
    let oS = document.createElement('script');
    // oS.src = json.url + '? ' +new URLSearchParams(json.data) + '&'+json.callback+'='+fnName;
    json.data[json.callback] = fnName; //cb=jquery_231231
    oS.src = json.url + '? ' + new URLSearchParams(json.data);
    document.querySelector('head').appendChild(oS);
    oS.remove();
}

Copy the code
// Server side

// Create a server
const http = require('http');
// Create a service
let sql = [
    {
        user: 'Tom'.password: 123
    },
    {
        user: 'Jess'.password: 1234
    },
    {
        user: 'Alex'.password: 12345}];const app = http.createServer((request, response) = > {
    let url = request.url; // Accept the request sent by the client (key=val&key2=val2... This argument is a string.
    let obj = {};
    if(url ! = ='/favicon.ico') {
        // Convert a string into an array, and then an array into an object
        url.split('? ').split('&').forEach(item= > {
            let ary = item.split('=');
            console.log(ary)
            obj[ary[0]] = ary[1];
        });
        // Check if there is a user name sent in the array
        let isExist = sql.find(e= > e.user === obj.user);
        console.log(isExist)
        // Set it in Chinese
        response.setHeader('Content-Type'.'text/html; charset=utf-8');
        // If there is one in the data array, the user name is occupied
        // obj.cb is the data returned by the background to the foreground
        if (isExist) {
            response.write(obj.cb + "({code:1, MSG :' username already registered '})");
        } else {
            response.write(obj.cb + "({code:0, MSG :' register successfully '})"); } response.end(); }})// Port listener
app.listen(80)
Copy the code

Post request write interface

fetch('/post', {body:'user=xiaoqiang'.method:'post'.headers: {'Content-Type':'application/x-www-form-urlencoded'
    }
    }).then(e= >e.json())
    .then(d= >{
    console.log(d);
});

Copy the code
// Server side
const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
// const 

let sql = ['zhiqiang']
http.createServer((req,res) = >{
    let url = req.url;
    if(url ! = ='/favicon.ico') {/ / files
        if(url.includes('.html')) {try {
                let d = fs.readFileSync('./www'+url);
                res.write(d.toString());
            } catch (error) {
                let er = fs.readFileSync('./www/404.html');
                res.write(er.toString());
            }
            res.end();
        }else{
            / / interface

            if(url === '/post') {let str = ' ';
                req.on('data',(d)=>{
                    // console.log(d.toString())
                    str += d;
                });

                req.on('end', () = > {// console.log(str.toString(),111);
                    let obj = querystring.parse(str);
                    // console.log(.user)
                    res.setHeader('Content-Type'.'text/html; charset=utf-8');
                    if(sql.includes(obj.user)){
                        res.write(JSON.stringify({code:0.msg:"Failure"}));
                    }else{
                        res.write(JSON.stringify({code:1.msg:"Success"}));
                    }
                    res.end();
                });
            }
        }
    }
    
}).listen(80);



Copy the code

= = = =

There’s a bunch of project code on the server, and there’s either server-side code or client-side code on the server, which we usually put in the static folder

Static /publice: all items that are returned to the client by the server, rendered and parsed by the client browser (front-end items: pages, CSS, JS, images, etc.)

Server.js: all need to be executed on the server side based on Node (backend project: usually only JS)