The artifact nodejs of javascript development back-end program

brief introduction

Although javascript can always be used as a server-side programming language, it is more displayed in front of the world in a client-side programming language. Maybe javascript itself forgot that it could also do server-side programming until the birth of nodejs in 2009.

The history of nodejs

As an explanatory language, javascript does not need to be compiled like C or C + +. But in the early days, the execution efficiency of javascript engine was relatively low, so javascript can only do dom operations.

With the rise of ajax and modern web2 With the development of 0 technology, mainstream browser developers try their best to improve the execution efficiency of JavaScript. Finally, chrome V8 appeared. Chrome V8 is the open-source JavaScript engine of Chromium project, which greatly improves the execution efficiency of JavaScript.

nodejs was reborn with V8.

nodejs has received great attention since its birth. There are still many developers who compare javascript. And how attractive it is for a language to be universal.

Nodejs has experienced 11 years of development from 2009 to 2020. Compared with its predecessor javascript, nodejs is still very young, but because of its openness and inclusiveness, nodejs is developing at a very fast speed.

Introduction to nodejs

Nodejs greatly improves the processing efficiency of nodejs with the help of V8 engine and a set of asynchronous I/O native functions.

Asynchronous IO should be clear to all of us. Compared with synchronous IO, threads do not need to be blocked and can handle other more meaningful things. Only resume the operation when the response returns, so CPU time will not be wasted.

Let's take a brief look at the IO model of nodejs:

A good language needs a good ecosystem, because the language itself can only provide some basic operations, and we also need a third-party system to enrich the ecology of the language.

The npm warehouse of nodejs hosts the world's largest open source library ecosystem.

Basically, using nodejs, you can achieve most of the functions you need.

Another feature of nodejs is simplicity. Consider our most commonly used web applications. If they are written in java, it is very troublesome. You also need a web server.

In nodejs, everything is so simple:

const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('welcome to www.flydean.com\n')
})

server.listen(port, hostname, () => {
  console.log(`please visit http://${hostname}:${port}/`)
})

The above code creates a web service and listens on port 3000,

We first introduce the http module for http processing.

Using HTTP's createServer() method will then create a new HTTP server and return it.

Inside the createServer method, we can set the object to be returned.

Finally, enable server Listen function to listen to specific ports and servers. When the service is ready, it will call the following callback function to execute specific commands.

Every time a new request is received, the request event will be triggered. The request event can pass two parameters:

  • Request is an HTTP Incomingmessage object, which provides the details of the request.
  • response is an HTTP Serverresponse object, which is used to return data to the caller.

In the above example, instead of using request, we directly built the returned object using response.

We set the statusCode and header, and finally use end to close the response.

This is a simple nodejs program.

The running environment of nodejs

nodejs, as a kind of js, is an interpretative language. Generally, there are two operation modes of interpretative language.

One is to run directly, the other is to open an interpretative environment and run in it, and nodejs is no exception.

It's easy to run directly. After we write the nodejs program, such as app JS, run directly as follows:

node app.js

If you execute the node command directly, the REPL mode will be turned on:

node
Welcome to Node.js v12.13.1.
Type ".help" for more information.
>

REPL, also known as run evaluation print loop, is a programming language environment (mainly console window). It uses a single expression as user input and returns the result to the console after execution.

What does REPL do?

First, we can run some test methods directly in REPL and verify the output results.

For example:

> console.log('www.flydean.com');
www.flydean.com

In addition, REPL has some more useful functions. We know that everything in JS is an object, such as the http object mentioned above. What if we want to know the general structure of http object?

Simply enter http in REPL environment:

> http
{
  _connectionListener: [Function: connectionListener],
  METHODS: [
    'ACL',         'BIND',       'CHECKOUT',
    'CONNECT',     'COPY',       'DELETE',
    'GET',         'HEAD',       'LINK',
    'LOCK',        'M-SEARCH',   'MERGE',
    'MKACTIVITY',  'MKCALENDAR', 'MKCOL',
    'MOVE',        'NOTIFY',     'OPTIONS',
    'PATCH',       'POST',       'PROPFIND',
    'PROPPATCH',   'PURGE',      'PUT',
    'REBIND',      'REPORT',     'SEARCH',
    'SOURCE',      'SUBSCRIBE',  'TRACE',
    'UNBIND',      'UNLINK',     'UNLOCK',
    'UNSUBSCRIBE'
  ],
  STATUS_CODES: {
    '100': 'Continue',
    '101': 'Switching Protocols',
    '102': 'Processing',
    '103': 'Early Hints',
    '200': 'OK',
    '201': 'Created',
    '202': 'Accepted',
    '203': 'Non-Authoritative Information',
    '204': 'No Content',
    '205': 'Reset Content',
    '206': 'Partial Content',
    '207': 'Multi-Status',
    '208': 'Already Reported',
    '226': 'IM Used',
    '300': 'Multiple Choices',
    '301': 'Moved Permanently',
    '302': 'Found',
    '303': 'See Other',
    '304': 'Not Modified',
    '305': 'Use Proxy',
    '307': 'Temporary Redirect',
    '308': 'Permanent Redirect',
    '400': 'Bad Request',
    '401': 'Unauthorized',
    '402': 'Payment Required',
    '403': 'Forbidden',
    '404': 'Not Found',
    '405': 'Method Not Allowed',
    '406': 'Not Acceptable',
    '407': 'Proxy Authentication Required',
    '408': 'Request Timeout',
    '409': 'Conflict',
    '410': 'Gone',
    '411': 'Length Required',
    '412': 'Precondition Failed',
    '413': 'Payload Too Large',
    '414': 'URI Too Long',
    '415': 'Unsupported Media Type',
    '416': 'Range Not Satisfiable',
    '417': 'Expectation Failed',
    '418': "I'm a Teapot",
    '421': 'Misdirected Request',
    '422': 'Unprocessable Entity',
    '423': 'Locked',
    '424': 'Failed Dependency',
    '425': 'Unordered Collection',
    '426': 'Upgrade Required',
    '428': 'Precondition Required',
    '429': 'Too Many Requests',
    '431': 'Request Header Fields Too Large',
    '451': 'Unavailable For Legal Reasons',
    '500': 'Internal Server Error',
    '501': 'Not Implemented',
    '502': 'Bad Gateway',
    '503': 'Service Unavailable',
    '504': 'Gateway Timeout',
    '505': 'HTTP Version Not Supported',
    '506': 'Variant Also Negotiates',
    '507': 'Insufficient Storage',
    '508': 'Loop Detected',
    '509': 'Bandwidth Limit Exceeded',
    '510': 'Not Extended',
    '511': 'Network Authentication Required'
  },
  Agent: [Function: Agent] { defaultMaxSockets: Infinity },
  ClientRequest: [Function: ClientRequest],
  IncomingMessage: [Function: IncomingMessage],
  OutgoingMessage: [Function: OutgoingMessage],
  Server: [Function: Server],
  ServerResponse: [Function: ServerResponse],
  createServer: [Function: createServer],
  get: [Function: get],
  request: [Function: request],
  maxHeaderSize: [Getter],
  globalAgent: [Getter/Setter]
}

The concise structure of http objects is directly output. We can also use the tab button to automatically complete the http method:

> http.
http.__defineGetter__      http.__defineSetter__      http.__lookupGetter__      http.__lookupSetter__      http.__proto__             http.constructor
http.hasOwnProperty        http.isPrototypeOf         http.propertyIsEnumerable  http.toLocaleString        http.toString              http.valueOf

http.Agent                 http.ClientRequest         http.IncomingMessage       http.METHODS               http.OutgoingMessage       http.STATUS_CODES
http.Server                http.ServerResponse        http._connectionListener   http.createServer          http.get                   http.globalAgent
http.maxHeaderSize         http.request

PREL also supports some specific point operations:

> .help
.break    Sometimes you get stuck, this gets you out
.clear    Alias for .break
.editor   Enter editor mode
.exit     Exit the repl
.help     Print this help message
.load     Load JS from a file into the REPL session
.save     Save all evaluated commands in this REPL session to a file

PERL also has a special variable, If you enter after some codes, The result of the last operation will be printed.

process

The process object is a global variable that provides information about the current node JS process and control it. As a global variable, it is always available to node JS application, no need to use require(). It can also be accessed explicitly using require ().

Because process represents the process information of nodejs, it can handle process termination, read environment variables, receive command line parameters and so on.

Terminate process

Let's first look at how to use process to terminate a process:

process.exit(0)

0 indicates normal exit. Of course, we can pass in different exit codes to indicate different meanings.

Under normal circumstances, if no asynchronous operation is waiting, the node JS will exit with status code 0. In other cases, the following status code will be used:

1 uncapped exception - an uncapped exception that is not handled by the domain or 'uncaughtException' event handler.

2 - not used (Bash reserved for internal abuse)

3 internal JavaScript parsing error - node The javascript source code inside JS caused a syntax parsing error in the boot process. Generally, it is only in the development of node JS itself.

4 internal JavaScript execution failure - guide the process to execute node JS internal javascript source code, the return function value failed. Generally, it is only in the development of node JS itself.

5 fatal error - there is a fatal error in V8. A typical message is a message printed from stderr with FATALERROR as the prefix.

6 internal exception handling of non function - an internal exception has occurred, but the internal exception handling function is set to a non function or cannot be called.

Internal exception handling runtime failure - there is an exception that cannot be caught. When trying to handle this exception, the handler itself threw an error. For example, if a 'uncaughtException' or domain The on ('error ') handler threw an error.

8 - not used in previous versions of node JS, exit code 8 sometimes indicates an uncapped exception.

You don't have to fill in an option 9, or you don't have to fill in an unknown value.

10 internal JavaScript runtime failure - when calling the boot function, the boot process executes node JS internal javascript source code throws an error. Generally, it is only in the development of node JS itself.

12 unavailable commissioning parameters

13 unfinished top level wait: Promise passed in by await has not called the resolve method

128 exit signal - if node JS receives a fatal signal, such as SIGKILL or sigup, its exit code will be 128 plus the code value of the signal. For example, the value of signal SIGABRT is 6, so the expected exit code will be 128 + 6 or 134.

We can monitor signal events through the on method of process:

process.on('SIGTERM', () => {
  server.close(() => {
    console.log('process aborted')
  })
})

What is a signal? The signal is a POSIX internal communication system: Send a notification to the process to inform it of the event.

Or we can send this signal from within the program:

process.kill(process.pid, 'SIGTERM')

env

Because the process process deals with the external environment, process provides the env attribute, which carries all the environment variables set when starting the process.

By default, node in env_ env is set to development.

process.env.NODE_ENV // "development"

We can change this environment variable to switch different running environments of nodejs.

argv

process provides argv to receive external parameters.

For example:

node app.js joe

argv is an array containing all the command line call parameters.

In the above example, the first parameter is the full path of the node command. The second parameter is the full path of the file being executed. All other parameters start at the third position.

To get joe, we can do this:

const args = process.argv.slice(2)
args[0]

In the case of key=value, we can pass the parameters in this way and use the minimast library to process the parameters:

node app.js --name=joe

const args = require('minimist')(process.argv.slice(2))
args['name'] //joe

CLI interaction

Starting from nodejs7, nodejs provides a readline module, which can be accessed from process Stdin get input:

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})

readline.question(`how are you?`, answer => {
  console.log(`${answer}!`)
  readline.close()
})

If you need more complex operations, you can use inquirer js:

const inquirer = require('inquirer')

var questions = [
  {
    type: 'input',
    name: 'hello',
    message: "how are you?"
  }
]

inquirer.prompt(questions).then(answers => {
  console.log(`${answers['hello']}!`)
})

exports module

nodejs has a built-in module system. When we need to use the functions provided by other LIBS, we can use require to introduce modules exposed by other LIBS.

However, the premise is that the lib needs to be exposed, that is, the module corresponding to exports comes out.

There are two ways to export nodejs objects: module Exports and add the object as an attribute of exports.

Let's first look at the first method. The square module is defined in square JS:

module.exports = class Square {
  constructor(width) {
    this.width = width;
  }

  area() {
    return this.width ** 2;
  }
};

In the following example, bar JS uses the square module that exports the square class:

const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`mySquare The area is ${mySquare.area()}`);

Look at the second way, define a circle js:

const { PI } = Math;

exports.area = (r) => PI * r ** 2;

exports.circumference = (r) => 2 * PI * r;

use:

const circle = require('./circle.js');
console.log(`The area of a circle with a radius of 4 is ${circle.area(4)}`);

Both can export specific modules, but module Exports will only export specific objects, while exports is to add objects as the properties of exports. We also need to find the properties of objects according to the property name.

nodejs API

Besides http, process and nodejs mentioned above, nodejs also provides many other very useful API s:

nodejs framework

In addition to the basic nodejs, nodejs has many excellent frameworks. With these frameworks, we can make the construction of nodejs programs easier and more powerful.

Like AdonisJs, express, koa, socket Wait.

Author: what about the flybean program

Link to this article: http://www.flydean.com/nodejs-kickoff/

Source of this article: flybean's blog

Welcome to my official account: the most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Tags: node.js

Posted by tunari on Tue, 03 May 2022 22:03:52 +0300