Node.js routing, front-end tool for asynchronous processes

 

Upload custom package npm.js

Note: Remember to send mail to activate Note: switch your source nrm npm Note: Do not pack your name and repeating other people's steps: 1. Log on account npm npm adduser

  1. Upload

    npm publish

The basic principle of the back-end routing node

  • Htpp done through the module. In fact, the back-end routing is the web server

  • Route generation:

    * Previously, a multi-page, click a link to open a new page.

    * Now popular is a single page, there is only one index, replacing the contents inside using a template.

const http = require('http')
​
const host = 'localhost'
​
const fs = require('fs')
​
const port = 6868;
​
http.createServer((req, res) => {
        res.writeHead(200, {
            'Content-type': 'text/html;charset=utf8'
        })
        switch (req.url) {
            case '/home':
                res.write('home')
                res.end()
​
                break;
            case '/shopcar':
                fs.readFile('./static/shopcar.html', 'utf8', (error, docs) => {
                    res.write(docs)
                    res.end()
                })
            default:
                break;
            Case '/1.jpg': 
                fs.readFile ( './ static / 1.jpg', (error, docs) => { 
                    res.writeHead (200 is, { 'the Type-the Content': 'Image / JPEG'} ); // output type 
                    // binary image is transmitted 
                    res.write (docs, 'binary') 
                    res.end () 
                }) 
                BREAK; 
            Case '/index.js': 
                fs.readFile (' static ./ /js/index.js', (error, docs) => { 
                    // binary image is transmitted 
                    res.write (docs) 
                    res.end () 
                }) 
                BREAK; 
                BREAK;
        }
    }) 
    .Listen (Port, Host, () => { 
        the console.log ( `server runs: HTTP: // $ {Host}:` $ {Port}) 
    })

 

npm script

The concept: npm script refers to scripts in the field package.json

Understanding package.json

  • package.json project dependencies information is recorded and npm script commands a configuration file

    Project dependencies information:

    * Dependencies of dependencies production environment

    * Dependencies devDependencies development environment used

  • Script command:

    * Npm init -y initialization

    * Npm run dev & npm run app all executing the command, the final output

    * Npm run dev && npm run app in order to perform

 1 //分别创建case.js与case2.两个文件
 2  3 {
 4     "name": "3-jiaoben",
 5     "version": "1.0.0",
 6     "description": "",
 7     "main": "case.js",
 8     "scripts": {
 9         "test": "echo \"Error: no test specified\" && exit 1",
10         "dev": "node case.js",
11         "app": "node case2.js"
12 13     },
14     "keywords": [],
15     "author": "",
16     "license": "ISC"
17 }

 

 

Asynchronous front-end workflow tools

javascript is single-threaded, in order to perform a task, you want to allow smooth implementation of the task, you need to use asynchronous. The asynchronous task into a queue, perform the task again after the end of the queue of the main thread execution

  • The front end of the asynchronous mode of operation

    1: the traditional way: callbacks, events

    2: Front asynchronous process tool (the package out of function, a library):

    es6 Promise

    es6 Generator

    es6-es8 async function

    Node in the asynchronous processing tools -> nextTi, steImmediate

    Third-party libraries -> async.js

  • Pormise

    . 1 const = PSE1 new new Promise ((Resolve, reject) => { // Resolve will not complete successfully changed, reject unfinished failure becomes 
    2          Resolve ( 'a task' )
     . 3      }). The then (Data => {
     . 4          the console.log (Data);
     . 5  . 6     })
     . 7      . the catch (error => {
     . 8 IF (error) the throw error; // throws an error, the process will be interrupted at this time 9     })
     10 . 11 12 is pse2 = const new new Promise ((Resolve, Reject) => {
              
       13 is          the setTimeout (() => {
     14              Resolve ( 'Task II' )
     15          }, 2000 )
     16      }) the then (Data =>. {
     . 17          the console.log (Data);
     18 is  . 19     })
     20 is      . The catch (error = > {
     21 is IF (error) the throw error;
     22 is     })
     23 is 24 // two methods promise to provide a core 25 // Promise.all ([promise example 1, promise example 2]) 26 is // Promise.race ([ promise example 1, promise example 2])             
     
     
    27  28 29 // Promise 30 //      .all ([PSE1, pse2]) // perform all tasks 31 is //      .then (() => {// (Data) => {} no value can not give 32 //          the console.log ( "task three '); 33 is //      }) 34 is // the console.log (" main thread "); 35 // output at this time: a main thread, a task, the task two, three tasks 36 37 [ Promise
     38 is     .race ([PSE1, pse2])
     39      .then (() => {
     40          the console.log ( "task three ' );
     41 is 42 is     })
     43  
     
     
     
     
     
     
         the console.log ( "main thread" );
     44  // output at this time: a main thread, a task, the task three, two tasks 
    45  46 is // All tasks sequentially executed, even if there is a delay task, the task must Peer Delayed introduction to perform subsequent tasks 47 // Race who quickly who should perform [1563348372761]! (C: \ Users \ Administrator \ AppData \ Roaming \ typora \ typora-user-images \ 1563348372761.png) 
     

     

Reference material

  1. Promise https://blog.csdn.net/MrJavaweb/article/details/79475949

  2. Generator https://www.cnblogs.com/imwtr/p/5913294.html

  3. Async-await

    • The inner layer to the outer layer to return the requested data using the results

    • Functional generator function package Async + spawn automatic actuator function

  4. Node.js in nextTick () and setimmediate () https://www.cnblogs.com/5ishare/p/5268273.html

  5. async library https://caolan.github.io/async/

 

Guess you like

Origin www.cnblogs.com/jxqw/p/11204859.html