Introduction to the

Javascript has always been a server-side programming language, but it was mostly presented as a client-side programming language. Perhaps javascript itself forgot that it could do server-side programming, until NodeJS came along in 2009.

The history of nodejs

As an interpreted language, javascript does not need to be compiled like C or C++. But in the early days,javascript engines were inefficient, so javascript could only do DOM manipulation.

With the rise of ajax and the development of modern web2.0 technology, mainstream browser developers tried their best to improve the efficiency of javascript execution, and finally Chrome V8 emerged. Chrome V8 is the open source javascript engine of the Chromium project. The efficiency of javascript execution has been greatly improved.

Nodejs is reborn from V8’s ashes.

Nodejs has received a lot of attention since its inception. There are a lot of javascript developers out there. And how attractive it is for a language to be able to use both the front and back ends.

Nodejs 14, from 2009 to 2020, has gone through 11 years of history. Compared with its predecessor javascript, nodeJS is still young, but because of its openness and inclusiveness, NodeJS is developing at a very fast pace.

Introduction of nodejs

Nodejs uses the V8 engine and a set of asynchronous I/O native features to greatly improve nodeJS processing efficiency.

Asynchronous IO as we all know, threads don’t block and can do other things that make more sense than synchronous IO. The operation is only resumed when the response returns, so no CPU time is wasted.

Let’s take a quick look at the NODEJS IO model:

A good language needs a good ecosystem, because the language itself can only provide the most basic operations, and we need third-party systems to enrich the language ecosystem.

Nodejs’ NPM repository hosts the largest open source library ecosystem in the world.

You can basically do most of the things you need with NodeJS.

Another aspect of NodeJS is its simplicity. If you think about the most common Web applications, writing them in Java is a hassle, and you 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}/ `)})Copy the code

The above code creates a Web service that listens on port 3000,

We first introduced the HTTP module for HTTP processing.

The createServer() method using HTTP then creates a new HTTP server and returns it.

Inside the createServer method, we can set the object to return.

Finally, the server.listen function is enabled to listen to specific ports and servers. When the service is ready, the following callback function will be invoked to execute specific commands.

Each time a new request is received, the Request event is raised. The request event can pass two parameters:

  • Request is an HTTP. IncomingMessage object that provides details about the request.
  • Response is an HTTP. ServerResponse object that returns data to the caller.

In the above example, instead of using Request, we built the returned object directly using Response.

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

This is a simple nodeJS program to use.

Nodejs running environment

Nodejs, as a kind of JS, is an interpreted language. Generally, interpreted languages run in two ways.

Either you run it directly, or you run it in an interpreted environment, and NodeJS is no exception.

After writing a nodejs program, such as app.js, we can run it like this:

node app.js
Copy the code

REPL mode is enabled if you execute the node command directly:

node
Welcome to Node.js v1213.1..
Type ".help" for more information.
>
Copy the code

REPL, also known as run evaluation Print loop, is a programming language environment (primarily console window) that takes a single expression as user input and returns the result to the console after execution.

What does a REPL do?

First, we can run some test methods directly in the REPL to validate the output.

Like this:

> console.log('www.flydean.com');
www.flydean.com
Copy the code

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

Just type HTTP in the 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]
}
Copy the code

We can also use the TAB button to automatically complete HTTP methods:

> 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
Copy the code

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
Copy the code

PERL also has a special variable _ that, if you type _ after some code, prints the result of the last operation.

process

The Process object is a global variable that provides information about and controls the current Node.js process. As a global variable, it is always available to Node.js applications without requiring require(). It can also be accessed explicitly using require().

Since process represents nodeJS process information, it can handle process termination, read environment variables, receive command-line arguments, and so on.

Terminate the process

Let’s look at how to terminate a process using process:

process.exit(0)
Copy the code

0 means normal exit. Of course, we can pass in different exit codes with different meanings.

Normally, if no asynchronous operation is waiting, Node.js exits with status code 0. Otherwise, the following status code is used:

1 uncaughtException – an exception that has not been caught and is not handled by domain or ‘uncaughtException’ event handlers.

2 – Not used (Bash is reserved for internal abuse)

Internal JavaScript parsing error – JavaScript source code inside Node.js caused a parsing error in the boot process. It usually only occurs during development of Node.js itself.

4 Internal JavaScript execution failure – The boot process failed to return function values while executing JavaScript source code inside Node.js. It usually only occurs during development of Node.js itself.

Fatal error – There was a fatal error in V8. Typically, messages printed from stderr are prefixed with FATALERROR.

Non-function internal exception handling – An internal exception occurs, but the internal exception handler is set to non-function or cannot be called.

Internal exception handling failed at runtime – There was an exception that could not be caught, and the handler itself threw an error while trying to handle the exception. For example, if an ‘uncaughtException’ or domain.on(‘error’) handler throws an error.

8 – Not used. In previous versions of Node.js, exit code 8 sometimes indicates an exception that was not caught.

9 – Unavailable parameter – An unknown option is not identified, or a required option is not specified.

Internal JavaScript runtime failure – The bootstrap process executing the JavaScript source code inside Node.js throws an error when calling the bootstrap function. It usually only occurs during development of Node.js itself.

12 Unavailable debugging parameters

13 Unfinished top-level Await: Await passed Promise never calls the resolve method

128 exit signal – If Node.js receives a fatal signal, such as SIGKILL or SIGHUP, its exit code will be 128 plus the signal’s code value. For example, the signal SIGABRT has a value of 6, so the expected exit code would be 128 + 6 or 134.

We can listen for signal events using the on method of process:

process.on('SIGTERM'.() = > {
  server.close(() = > {
    console.log('Process terminated')})})Copy the code

What is a signal? A signal is a POSIX internal communication system: a notification is sent to a process to inform it of an event.

Or we can send this signal from within the program:

process.kill(process.pid, 'SIGTERM')
Copy the code

env

Because process processes interact with external environments, process provides the env attribute, which holds all of the environment variables set when the process is started.

By default, NODE_ENV in env is set to development.

process.env.NODE_ENV // "development"
Copy the code

We can change this environment variable to switch between different running environments for NodeJS.

argv

Process provides argv to receive external parameters.

Such as:

node app.js joe
Copy the code

Argv is an array containing all command line call arguments.

In the example above, the first argument is the full path to the node command. The second argument is the full path to the file being executed. All other parameters start in the third position.

To get Joe, we can do this:

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

In the case of key=value, we can pass parameters like this and use the Minimist library to handle parameters:

node app.js --name=joe

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

CLI interaction

Starting with nodejs7, NodeJS provides the readline module, which takes input from process.stdin:

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

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

If more complex operations are needed, Inquirer.js can be used:

const inquirer = require('inquirer')

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

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

Exports module

Nodejs has a built-in module system, and when we need to use functionality provided by other lib, we can use require to import modules exposed by other Lib.

But only if the lib needs to be exposed, i.e., exports corresponding modules.

Nodejs exports objects in two ways: module.exports and adding objects as exports properties.

The square module is defined in square.js:

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

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

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(The area of 'mySquare' is${mySquare.area()}`);
Copy the code

The second way is to define a circle.js:

const { PI } = Math;

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

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

Use:

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

Exports exports only specific objects. Exports is an attribute that adds an object to exports. We also need to find the attribute of the object based on the attribute name.

nodejs API

In addition to the HTTP, Process, and Nodejs apis we mentioned above, nodejs provides a number of other very useful apis:

The framework of nodejs

In addition to basic NodeJS, nodeJS has many excellent frameworks that make building NodeJS applications easier and more powerful.

Like AdonisJs, Express, KOa, socket.io, etc.

Author: Flydean program stuff

Link to this article: www.flydean.com/nodejs-kick…

Source: Flydean’s blog

Welcome to pay attention to my public number: “procedures those things” the most popular interpretation, the most profound dry goods, the most concise tutorial, many you do not know the small skills you find!