Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Why learn Node?

  • IO advantage

    • For file reads and writes,Node uses non-blocking IO
    • Traditional IO processes files while they are read or written, and code execution waits, wasting performance
    • Non-blocking IO hands the read and write operations to the CPU while the code executes normally, reducing wasted wait performance
  • Application scenarios

    • Application: webpack/gulp/ NPM/HTTP-server /json-server
    • Middle-tier server in charge of I/O reading and writing (Tmall middle-tier I/O server)

NodeJS characteristics

  • It is a chrome V8 port, parsing and executing the same code mechanism as browser JS

  • It follows the JavaScript syntax and extends the functionality it needs

  • Conclusion: NodeJS is a back-end language with the ability to manipulate files and create and manipulate servers

    • The syntax is JavaScript syntax and the code runs on the Chrome V8 engine

The basic use

  • Install node-v-xx.msi from node-V-xx. msi
  • Check whether node -v is successfully installed
  • Run the program node. /xxx.js

Introduction to Built-in Objects


classification

  • Global objects: accessible whenever and wherever
  • Core object: ask for the system, introduce can be used
  • Custom objects: Import objects by path

Process (global object)

  • Environment variables are almost different from system to system, and a specific value in the environment variable can be used to distinguish between different machines

  • Process. env is an object that we can pass through. Property name to get the value of a specific environment variable

    • Set a specific environment variable to make it easy to differentiate between different machines to run differently for production/development environments
  • Process. argv gets command line arguments

Filename /dirname (global object)

  • __filename Specifies the absolute path to the current running file
  • __dirName Absolute path of the current running file

Nodejs implementation specification

  • CommonJS: Standard for the JavaScript language to run as a back-end language

    • Have what ability, how should do, for example: have server function/can operate file…..

    • How to write a Module:

      • 1: require(‘ module name (id)’)
      • Module. exports = external data
      • 3: A file is a module

Core object PATH

  • 1:const path = require('path');

  • Path -> is good at handling paths, but it is not responsible for determining whether a path has a file

  • Join and fix path.join(__dirname,’a’,’b’); Use the current directory /a/b

  • Path.resovle ('./ XXX ') turns to absolute

  • Takes a valid path string and converts it to an object

    • let pathObj = path.parse(mypath);
  • Takes a path object and converts it to a string path

    • let str = path.format(pathObj);
{root: 'C: \', dir: sun wukong 'C: \ Users \', base: 'great. TXT', / / this property can be used to modify the file name and the suffix ext: '. TXT ', name: 'great news'}Copy the code
  • Note: The path object is handy for manipulating paths, and for fetching: parse to objects, convert format to strings. join and modify…. For modifying path objects, you can change them with the base property, not name,ext

The module

  • disadvantages

    • In JS, logic is involved, and in HTML, reference order is considered for logical objects

    • All objects are global by default, with conflicting names

    • Commonjs specification

    • A file is a module

      • Import with require (‘. / XXX. Js’);
      • Module. exports = XXX;
      • Variables declared in each module belong to the scope within the module

Fs file module

  • File to read and write
  • Other features
  • Extension is introduced

Manipulating file objects

  • IO

    • I: input input
    • O: the output output
    • File operations are IO
  • The process of copying files, I: through the computer, storing files to the clipboard

    • Paste to a specified directory: O: Write out the data on the clipboard to a specified directory on the computer
  • Node has two types of IO operations

    • Synchronous IO

      • One line of code (read file) does not execute complete… Subsequent code cannot be executed
    • Asynchronous IO (Recommended)

      • A line of code (reading/writing file) does not complete (reading/writing)… Subsequent code can also be executed
    • Code experience:

      • Read and write files
      • const fs = require('fs'); // This name must be used // read fs.readfile (path, callback); // write fs.writefile (path, data, callback);Copy the code
      • Conclusion: asynchronous file read/write parameter 1: both are paths, can be relative or absolute, the last parameter is callback function, callback function parameters, error object priority
  • The differences between synchronous and asynchronous I/OS are as follows: Synchronous I/OS block subsequent code execution, while asynchronous I/OS do not block subsequent code execution

Nginx load balancing

Package (folder)

  • Multiple files, effectively organized and managed by a unit
  • Leave an entrance

npm

  • You first have a package description file

  • Create a package description file NPM init

  • Download NPM install art-template [email protected] –save

    • Record depend on--save
  • Restore dependencies according to the Dependencies property in package.json file

    • Recovery packagenpm install
  • Uninstall a package NPM uninstall [email protected] –save

  • View package information

    • npm info jquery
  • View a field (version) in package information

    • npm info jquery versions
  • View the documentation for the package

    • npm docs jquery
  • Install the global command line tool

    • npm install -g http-server
  • Uninstall the global command line tool

    • npm uninstall -g http-server
  • View the download path of the global package

    • npm root -g

NRM is the image source management tool of the NPM

  • 1: global installationnpm install -g nrm
  • 2: View the available mirror sourcesnrm ls
  • 3: Switch the mirror sourcenrm use taobao

Package loading mechanism

  • We may need to identify in the future whether an entry in a package is the launcher we want
  • 1: Find the main property in the package name folder under node_modules
  • 2: uncommon: Find the package name.js under node_modules
  • 3: Find index.js in the package name folder under node_modules

HTTP core module


HTTP Hypertext transfer protocol

  • Protocol at least both -> HTTP both!!

  • Client (browser) -> Server

    • Native application (QQ) -> server

The process by which requests and responses interact

  • As shown in figure

The main object

  • Server object
  • Client object
  • Request message object (readable to the server)
  • Response message object (for the server, writable)

Procedure For creating a server

  • 1: introduces HTTP core objects
  • CreateServer (callback) using HTTP core objects. Creating a server object
  • 3: uses the server object. Listen (port, IP address) starts the server
  • 4: Callback (REq, RES) processes the response based on the request

The request object

  • Request the URL in the first linereq.url
  • Request mode in the first line of the requestreq.method
  • Data in the request headerreq.headersIt’s an object
  • Header information can also be used as a way to interact with the server

Gets the request body data

  • Code comparison
  • $(‘#xx’).on(‘submit’,function(e){})
  • Req. on(‘data’,function(d){d.tostring (); })

Querystring core object

  • querystring.parse(formStr)
  • Username =jack&password=123 Convert to the following
  • { username: ‘jack’, password: ‘123’ }

The response object

  • Response line 1 res.writehead (status code)

  • Write a response headers

    • Write back the message once

      • res.writeHead(200,headers)
    • Set header information multiple times

      • res.setHeader(key,value);
  • Write a response body

    • Write back the response body once

      • res.end();
    • Write back the response body multiple times

      • res.write();

Request and Response

  • Head of the line body
  • Content-type is a description of the request or response body data

Response body data

  • Res. Write (‘ string ‘| | to read binary data file)
  • Res. The end (‘ string ‘| | to read binary file)

Write back page

  • Heroes list
  • art-template http
  • This data can only be returned by accessing the GET request URL: /hero-list
  • Other requests return OK