NodeJS

Simply put, Node.js is JavaScript running on the server side.

When using Node.js, we are not only implementing an application, but also an entire HTTP server.

 

composition:

example:

// We use the require command to load the http module and assign the instantiated HTTP to the variable http

var http = require('http');//Use the http.createServer() method to create a server, and use the listen method to bind port 8888. Functions receive and respond to data through request, response parameters. http.createServer(function (request, response) { // Send HTTP header // HTTP status value: 200 : OK // Content type: text/plain response.writeHead(200, {'Content-Type': 'text/ plain'}); // Send response data "Hello World" response.end('Hello World\n');}).listen(8888);// The terminal prints the following information console.log('Server running at http: //127.0.0.1:8888/');

 

NPM :

NPM is a package management tool installed with NodeJS. It can solve many problems in NodeJS code deployment. Common usage scenarios are as follows:

l Allow users to download third-party packages written by others from the NPM server for local use.

l Allow users to download and install command-line programs written by others from the NPM server for local use.

l Allow users to upload their own packages or command-line programs to the NPM server for others to use.

You can test for a successful installation by typing "npm -v".

 

Install the module using the npm command:

example:

npm install express // Install the common Node.js web framework module express

 

After installation, the express package is placed in the node_modules directory under the project directory, so in the code, you only need to pass require('express') without specifying the third-party package path.

var express = require('express');

 

Global installation vs local installation:

The package installation of npm is divided into two types: local installation (local) and global installation (global). From the point of view of the command line, the only difference is whether there is -g, for example

npm install express # install locally npm install express -g # install globally

 

If the following error occurs:

npm err! Error: connect ECONNREFUSED 127.0.0.1:8087

The solution is:

$ npm config set proxy null

 

local installation

l 1. Put the installation package under ./node_modules (the directory where the npm command is run), if there is no node_modules directory, the node_modules directory will be generated under the directory where the npm command is currently executed.

l 2. You can import locally installed packages through require().

Install globally

l 1. Put the installation package under /usr/local or the installation directory of your node.

l 2. Can be used directly in the command line.

 

npm list -g //Query all globally installed modules

 

package.json is located in the module's directory and is used to define the properties of the package. Located at node_modules/express/package.json.

npm uninstall express //uninstall the module

npm ls //look at the package

 

npm update express //update module

npm search express //search module

To create a module, the package.json file is essential. We can use NPM to generate a package.json file that contains the basic results.

 

Version number (omitted)

https://docs.npmjs.com/ official documentation

http://npm.taobao.org/ Taobao NPM mirror

Mirroring is a type of redundancy. Data on one disk has an exact copy on another disk, which is mirroring.

 

The variable declaration needs to use the var keyword. If the var keyword is not used, the variable will be printed directly.

Variables using the var keyword can use console.log() to output the variable.

 

Multi-line expression:

... The symbol of three dots is automatically generated by the system, you can press Enter and Line Feed. Node will automatically detect if it is a continuous expression.

 

You can use the underscore (_) to get the result of the previous expression.

 

REPL command:

 

Asynchronous programming relies on callbacks to achieve, but it cannot be said that the program is asynchronous after using callbacks.

The callback function will be called after the task is completed. Node uses a large number of callback functions. All Node APIs support callback functions.

The first instance executes the program after the file has been read. In the second instance, we don't need to wait for the file to be read, so that the next code can be executed at the same time when the file is read, which greatly improves the performance of the program. Blocking is performed in order, and non-blocking does not need to be in order, so if we need to process the parameters of the callback function, we need to write it in the callback function.

 

Node.js is a single-process single-threaded application, but supports concurrency through events and callbacks, so the performance is very high.

Every API in Node.js is asynchronous and runs as a separate thread, uses asynchronous function calls, and handles concurrency.

Basically all event mechanisms in Node.js are implemented using the observer pattern in the design pattern.

Node.js single thread is similar to entering a while(true) event loop until no event observer exits, each asynchronous event generates an event observer, and the callback function is called if an event occurs.

 

Event driver:

When the web server receives a request, it closes it and processes it before serving the next web request.

When the request completes, it is put back on the processing queue, and when the head of the queue is reached, the result is returned to the user.

This model is very efficient and scalable because the webserver is always accepting requests without waiting for any read or write operations. (This is also known as non-blocking IO or event-driven IO)

In an event-driven model, a main loop is generated to listen for events, and when an event is detected, a callback function is triggered.

 

Node.js has a number of built-in events. We can bind and listen to events by introducing the events module and instantiating the EventEmitter class (the encapsulation of event triggering and event listener functions):

example:

 

The on function is used to bind the event function, and the emit property is used to trigger an event.

Other methods (omitted)

An EventEmitter object fires an error event if an error occurs during instantiation. The newListener event fires when a new listener is added, and the removeListener event fires when the listener is removed.

Remember the handling of the err event!

Most of the time we don't use EventEmitter directly, but inherit it in the object. Including fs, net, http, as long as the core modules that support event response are subclasses of EventEmitter.

 

Node.js Buffer:

The JavaScript language itself only has a string data type, not a binary data type.

But when dealing with streams like TCP or file streams, binary data must be used. Therefore, in Node.js, a Buffer class is defined, which is used to create a buffer area dedicated to storing binary data.

 

 

Create the Buffer class:

Output result:

 

Write to buffer:

example:

buf= Buffer.alloc(256).write("www.baidu.com");

//alloc() parentheses are hauls with insufficient space capacity, only part of the string will be written

console.log("Number of bytes written: "+buf);

 

Read data from buffer:

example:

 

Convert Buffer to JSON object:

example:

Other methods (omitted)

 

Node.js Stream (stream):

http://www.runoob.com/nodejs/nodejs-stream.html

 

Node.js module system:

A Node.js file is a module

Create a main.js file

var hello=require('./hello');

hello.world();

After creating a hello.js file

exports.world=function(){

console.log('Hello World');

}

Node.js provides two objects, exports and require, where exports is the interface exposed by the module, and require is used to obtain the interface of a module from the outside, that is, the exports object of the obtained module.

example:

Sometimes we just want to encapsulate an object into a module:

//hello.js function Hello() { var name; this.setName = function(thyName) { name = thyName; }; this.sayHello = function() { console.log('Hello ' + name); }; }; module.exports = Hello;

This way you can get the object directly:

//main.js var Hello = require('./hello'); hello = new Hello(); hello.setName('BYVoid'); hello.sayHello();

The only change to the module interface is to use module.exports = Hello instead of exports.world = function(){}. When the module is referenced externally, its interface object is the Hello object to be exported, not the original exports.

 

Where are the modules on the server side:

 

Node.js routing:

http://www.runoob.com/nodejs/nodejs-router.html

 

The global object in Node.js is global.

Note: Always use var to define variables to avoid introducing global variables, because global variables will pollute the namespace and increase the risk of code coupling. http://www.runoob.com/nodejs/nodejs-global-object.html

 

Node.js common tools:

http://www.runoob.com/nodejs/nodejs-util.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324839631&siteId=291194637