In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you about the use of nodejs, the artifact of javascript development back-end programs. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Let's take a look at it with the editor.
Brief introduction
Although javascript can always be a server-side programming language, it is more often displayed in the client-side programming language in front of the world. Maybe javascript forgot that he could do server-side programming until the advent of nodejs in 2009.
History of nodejs
As an interpretive language, javascript does not need to be compiled like C or C++. But in the early days, the execution efficiency of the javascript engine was relatively low, so javascript could only do dom operations.
With the rise of ajax and the development of modern web2.0 technology, mainstream browser developers try their best to improve the execution efficiency of javascript. Finally, Chrome V8 appears. Chrome V8 is the open source JavaScript engine of Chromium project, which greatly improves the execution efficiency of javascript.
Nodejs was reborn by V8.
Nodejs has received a great deal of attention since its birth. There are still a lot of developers comparing javascript. And how attractive it is that a language can be used at the front and back end.
Nodejs developed from 2009 to nodejs 14 in 2020, after 11 years of history, compared with its predecessor javascript 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 Imax O native functions.
Asynchronous IO should be clear to all of us that threads don't have to block and can handle other more meaningful things than synchronous IO. The operation is only resumed when the response is returned, so CPU time is not wasted.
Let's take a brief look at nodejs's IO model:
A good language needs to be matched by a good ecosystem, because the language itself can only provide the most basic operations, and we also need a third-party system to enrich the ecology of the language.
Nodejs's npm warehouse hosts the world's largest open source ecosystem.
Basically, you can achieve most of the functions you need with nodejs.
Another feature of nodejs is its simplicity. Consider our most commonly used web applications. If you write in java, it's 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 that listens on port 3000
We first introduce the http module for http processing.
Then using http's createServer () method creates a new HTTP server and returns it.
Inside the createServer method, we can set the object to be returned.
Finally, the server.listen function is enabled to listen on a specific port and server, and when the service is ready, the subsequent callback function is called to execute the specific command.
Whenever a new request is received, the request event is triggered, and the request event can be passed two parameters:
Request is a http.IncomingMessage object that provides the details of the request.
Response is a http.ServerResponse object that returns data to the caller.
In the above example, instead of using request, we use response to build the returned object directly.
We set up statusCode and header, and finally use end to turn off the response.
This is an easy-to-use nodejs program.
The operating environment of nodejs
Nodejs, as a kind of js, is an interpretive language. Generally, interpretive languages have two modes of operation.
One is to run directly, and the other is to open an interpretive environment in which nodejs is no exception.
It is easy to run directly. After we have written the nodejs program, such as app.js, we will run it like this:
Node app.js
If you execute the node command directly, REPL mode is turned on:
Node
Welcome to Node.js v12.13.1.
Type ".help" for more information.
>
REPL, also known as the run evaluation print cycle, is a programming environment (primarily a console window) that uses a single expression as user input and returns the results to the console after execution.
What is the purpose of REPL?
First, we can run some test methods directly in REPL to verify the output.
Like this:
> console.log ('www.flydean.com')
Www.flydean.com
In addition, REPL has some more useful features. We know that everything in JS is an object, such as the http object we mentioned above. What if we want to know the general structure of the http object?
Enter http directly in the REPL environment:
> http
{
_ connectionListener: [Function: connectionListener]
METHODS: [
'ACL', 'BIND',' CHECKOUT'
'CONNECT', 'COPY',' DELETE'
'GET', 'HEAD',' LINK'
'LOCK',' Mmurse SEARCHY, '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: {
'100miles: 'Continue'
'101 percent: 'Switching Protocols'
'102 percent: 'Processing'
'103 years: 'Early Hints'
'2000s:' OK'
'2018:' Created'
'202 years: 'Accepted'
'203 years: 'Non-Authoritative Information'
'204years:'No Content'
'205years: 'Reset Content'
'206years: 'Partial Content'
'207years: 'Multi-Status'
'208 years: 'Already Reported'
'226girls:'IM Used'
'300 million: 'Multiple Choices'
'301mm: 'Moved Permanently'
'302years: 'Found'
'303 years: 'See Other'
'304mm: 'Not Modified'
'305mm: 'Use Proxy'
'307 days: 'Temporary Redirect'
'308:' Permanent Redirect'
'400 million: 'Bad Request'
'401mm: '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 years: 'Range Not Satisfiable'
'417:' Expectation Failed'
'418: "I'm a Teapot"
'421 years: 'Misdirected Request'
'422 percent: 'Unprocessable Entity'
'423rd: 'Locked'
'424 hours: 'Failed Dependency'
'425:' Unordered Collection'
'426girls: 'Upgrade Required'
'428:' Precondition Required'
'4299: 'Too Many Requests'
'431mm: 'Request Header Fields Too Large'
'451mm: 'Unavailable For Legal Reasons'
'500miles: 'Internal Server Error'
'501mm: 'Not Implemented'
'502years: 'Bad Gateway'
'503 years: 'Service Unavailable'
'504': 'Gateway Timeout'
'505 years: 'HTTP Version Not Supported'
'506:' Variant Also Negotiates'
'507 days: 'Insufficient Storage'
'508': 'Loop Detected'
'509 years: '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]
}
After directly outputting the concise structure of the http object, 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 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, _, which, if typed 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 the use of 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 the process
Let's take a look at how to use process to terminate a process:
Process.exit (0)
0 means normal exit, of course, we can pass in different exit codes to indicate different meanings.
Normally, if no asynchronous operation is waiting, Node.js exits with a status code of 0. In other cases, the following status code is used:
1 uncaught exception-an uncaught exception that is not handled by the domain or 'uncaughtException' event handler.
2-not used (Bash is reserved to prevent internal abuse)
Internal JavaScript parsing error-the JavaScript source code inside Node.js caused a syntax parsing error during the boot process. It usually only occurs when developing Node.js itself.
4 Internal JavaScript execution failed-when the boot process executes the JavaScript source code inside Node.js, the return function value fails. It usually only occurs when developing Node.js itself.
5 fatal error-there is a fatal error in V8. Typically, messages are printed from stderr with the prefix FATALERROR.
6 non-function internal exception handling-an internal exception occurred, but the internal exception handler is set to a non-function or cannot be called.
7 Internal exception handling failed at run time-there was an exception that could not be caught, and the handler itself threw an error when trying to handle it. For example, if an 'uncaughtException' or domain.on (' error') handler throws an error.
8-unused, in previous versions of Node.js, the exit code 8 sometimes represented an uncaught exception.
9-unavailable parameter-an unknown option has not been determined, or a required option has not been filled in.
10 internal JavaScript runtime failure-when the boot function is called, the boot process executes the JavaScript source code inside the Node.js and throws an error. It usually only occurs when developing Node.js itself.
12 debugging parameters that are not available
13 incomplete Top-Level Await: the Promise passed in by await has not called the resolve method
Exit signal-if Node.js receives a fatal signal, such as SIGKILL or SIGHUP, its exit code will be 128 plus the code value of the signal. For example, the value of the signal SIGABRT is 6, so the expected exit code will be 128 + 6 or 134.
We can listen for signal events through the on method of process:
Process.on ('SIGTERM', ()) = > {
Server.close () = > {
Console.log ('process terminated')
})
})
What is a signal? A signal is an POSIX intercom system that sends notifications to processes to inform them of events that have occurred.
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 property, which carries all the environment variables that are set when the process is started.
By default, NODE_ENV in env is set to development.
Process.env.NODE_ENV / / "development"
We can change the environment variable to switch between different running environments of nodejs.
Argv
Process provides argv to receive external parameters.
For example:
Node app.js joe
Argv is an array of all command line invocation parameters.
In the above example, the first argument is the full path to the node command. The second parameter is the full path to the file being executed. All other parameters start at the third position.
To get the joe, we can do this:
Const args = process.argv.slice (2)
Args [0]
In the case of key=value, we can pass the parameters like this and use the minimist library to process the parameters:
Node app.js-name=joe
Const args = require ('minimist') (process.argv.slice (2))
Args ['name'] / / joe
CLI interaction
Starting with nodejs7, nodejs provides a readline module that can get 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 ()
})
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, and when we need to use other functions provided by lib, we can use require to introduce other modules exposed by lib.
But the premise is that the lib needs to be made public, that is, the corresponding module of the exports comes out.
There are two ways to export objects for nodejs: module.exports and adding objects as attributes of exports.
First, look at the first way. 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 (the area of `mySquare is ${mySquare.area ()} `)
Looking 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 radius 4 is ${circle.area (4)} `)
Both can export specific modules, but module.exports only exports specific objects, while exports adds objects as attributes of exports, and we also need to find the properties of objects based on the attribute name.
Nodejs API
In addition to the http,process we mentioned above, nodejs provides a number of other very useful API:
The framework of nodejs
In addition to the basic nodejs, nodejs has many excellent frameworks that make it easier and more powerful to build nodejs programs.
Like AdonisJs,express,koa,Socket.io and so on.
The above is the use of nodejs, an artifact used by javascript to develop back-end programs. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.