In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "what is the role of nodejs", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what is the role of nodejs" this article?
I. Overview
1. Html can be opened and run directly in the browser because the browser is the parser of html files.
Js files cannot be run directly in browsers because browsers do not support parsing js files, so a parser is needed to parse js files.
You can download and install the nodejs parser, and it comes with npm. You can run the js file directly through node.exe, in the form of a command line.
To run a js file, directly node + the name of the js file to be run or the js code, press enter
Js operates browsers, node operates computer systems, files, etc.
2. The editor can also be run directly. Webstorm is recommended.
3. In the Ecmascript section, node and js are actually the same, such as the definition of data types, syntax structures, and built-in objects
Top-level object in js: window
The top-level object in node: global, there is no concept of window
2. Module
Es6 is modularized through import export
Nodejs is modularized through require
Html introduces js files through script tags
1. In nodeJs, a js file is a module, and each module has its own scope
The variables we declare using var are not global, but belong to the
For example: 1.js
Var a = 100
Console.log (a) / 100
Console.log (global.a); / / undefined, which is not a variable under the global
Global.a = 200
Console.log (a); / / 100 is still the original 100 defined.
Console.log (global.a); / / it is 200 at this time.
2. Filename: indicates the absolute path of the current file
Dirname: indicates the absolute path of the directory where the current file is located
They are not global, but within the scope of the module
So global.filename is not accessible, return undefined
Console.log (filename); / / E:\ webstorm folder\ index.js
Console.log (_ _ dirname); / / E:\ webstorm folder
3. Module path
Require (); / / can be absolute path, relative path
You can't directly use require ("1.js") without. /. This loading method will load the core module in node, or the mousse in node_modules.
4. Find the file:
First, look up according to the file name of the loaded module.
If it is not found, the module file name is automatically suffixed with a .js suffix, and then look for it.
If it is not found yet, the module file name will be automatically suffixed with a .json suffix, and then look for it.
If it has not been found, the suffix .node is automatically added to the module file name, and then it is looked up.
If you haven't found it yet, you will report an error.
5 、
In a module, variables defined by var are scoped to the current module and cannot be accessed directly from the outside
If we want one module to be able to access variables defined in another module, we can do this by:
Use the variable as a property of the global object (not recommended)
Global.a = 100
Use the module object module, which is not global, but an object under each module
The module object module is used to save some information about the current module. There are many properties below:
A child object of exports: {}; / / module, through which local variables in a module can be exposed for external access
Because exports is also an object, declare a key value, which is the local variable, before exposing the variable.
Var a = 100% module.exports.name = a * * require (); / / the returned value is the module.exports object
6. Under the module scope, there is also a built-in module object, exports, which is actually module.exports
So:
Module.exports.name = a; can be written as exports.name = a
[note]: do not do this
Module.exports = [1pm 2pm 3]
Also do not: exports = [1jue 2jin3], just append the attribute, do not modify it
3. Global object global object
Local:
Filename
Dirname
Global:
Date object var d = new Date ()
Array var arr = new Array (1, 2, 3)
Timer
3-1. Process object (process object)-- Global object
Process = global.process / / true
It can be accessed anywhere, and through the properties and methods provided by this object, we can access and control the process of the currently running program.
1 、 process.argv
Console.log (process.argv); / / ['D:\ Program Files\ nodejs\ node.exe','E:\ webstorm folder\ 2.js']
The first is the parser and the second is the js file
If you take the parameters, the returned array will contain the parameters you brought in at run time
For example: node process.argv axiom 1 / / ['D:\ Program Files\ nodejs\ node.exe', 'E:\ webstorm folder\ 2.jskeeper dagger']
2 、 process.execPath
The absolute path to the executable file that opens the current process
3 、 env
Return user environment information
4 、 version
Returns node version information
5 、 versions
Returns node and node dependency package version information
6 、 pid
The pid process that returns the current process is node.exe
7 、 title
Returns the display name of the current process (Getters/Setters)
8 、 arch
Returns the current CPU processor architecture arm/ia32/x64
9 、 platform
Return to the current operating platform
10. Cwd ()
Returns the working directory of the current process
11. Chdir (directory)
Change the working directory of the current process
12. MemoryUsage ()
Returns the memory usage of the node process in byte
12. Exit (code)
Quit
13. Kill (pid)
Send information to the process
14 、 IO
A, stdin, stdout: standard input / output stream (IO)
Standard input device: a device that inputs data and information to a computer and serves as a bridge for communication between the computer and users or other devices.
For example: mouse, keyboard, camera, etc.
Standard output device: a terminal device of a computer hardware system that displays computer data or information in the form of numbers, characters, images, sounds, etc. For example: monitor, print, etc.
Stdin and stdout provide methods for manipulating input and output data, which are often called IO operations
Stdin: standard input stream
Stdout: standard output stream
Console.log (...) = process.stdout.write (...)
B. By default, the input stream is closed. To monitor and process the input stream data, you must first open the input stream.
/ / enable process.stdin.resume (); listen to the user's input data, and press enter process.stdin.on ('data',function (chunk) {console.log (' user input:'+ chunk);})
It will monitor all the time, and when the user has finished typing, press enter to display the data, and then press the button to still display the data entered for the second time.
4. Buffer class: similar array
1. Definition: a class for better manipulation of binary data
When we manipulate files or network data, we actually operate binary data streams; Node provides us with a more convenient class Buffer to manipulate this data flow, which is a global class, global.Buffer = = buffer
The JavaScript language itself has only string data types, not binary data types.
However, binary data must be used when dealing with streams such as TCP or files. So in Node.js, you define a Buffer class that is used to create a cache dedicated to binary data.
In Node.js, the Buffer class is a core library released with the Node kernel. The Buffer library provides a way for Node.js to store raw data, allowing Node.js to work with binary data, making it possible to use the Buffer library whenever you need to process data moved during an Ibank O operation in Node.js. The raw data is stored in an instance of the Buffer class. A Buffer is similar to an array of integers, but it corresponds to a piece of raw memory outside the V8 heap memory.
Buffer.alloc (size); create a Buffer object and assign it a space size of 8 bytes of size; when we allocate a space size for a buffer object, its length is fixed and cannot be changed. That is, no more content can be added in the future.
/ / the console shows hexadecimal
Buffer.from (array): returns a new Buffer instance initialized by the value of array (the element of the array passed in can only be a number, otherwise it will be automatically overwritten by 0), declared and assigned
Buffer.from (string [, encoding]): returns a new Buffer instance initialized by the value of string. Encoding defaults to utf8.
Let bf2 = Buffer.from ('miaov'); / / bf2.length 5 returns the number of bytes, not the string length
Let bf3 = Buffer.from ('wonderful taste'); / / bf3.length 6 A Chinese character occupies 3 bytes
2. Buffer class methods
Byte length of bf.length; / / buffer
Bf [index]; / / gets or sets the 8-bit byte content at the index index location
Bf.write (string, [offset], [length], [encoding]); / / write parameter string write data to buffer according to the parameter offset offset and the specified encoding encoding method
Bf.toString ([encoding], [start], [end]); / / returns a decoded string type based on encoding
Bf.toJSON (); / / returns a Buffer instance represented by JSON. JSON.stringify will be called by default to serialize this Buffer instance by string.
Bf.slice ([start], [end]); / / returns a new buffer that will have the same memory address as the old buffer reference
Note: modifying the slice slice of this new buffer instance will also change the original buffer
Bf.copy (targetBuffer [, targetStart [, sourceStart [, sourceEnd]])
Let bf2 = Buffer.from ('miaov'); console.log (bf2); / hexadecimal console.log (bf2.toString ()); / /' miaov'for (let iTun0) I {if (! err) {fs.writeFile (filename,'hello', (err) = > {if (err) {console.log ("file creation failed")} else {console.log ("file creation successful")})} else {fs.appendFile (filename,'-world') (err) = > {if (err) {console.log ('file append failed')} else {console.log ('file append successful')})}) / / synchronize if (! fs.existsSync (filename)) {console.log ('file created successfully'); fs.writeFileSync (filename,'hello')} else {console.log ('file appended successfully'); fs.appendFileSync (file)}
6. Fs.rename (oldPath,newPath,callback)
Rename
Synchronous version: fs.renameSync (oldPath,newPath)
7. Fs.stat (path,callback)
The status of reading file information, not the internal contents of the file. The return value is a json, including file type, file date, file size, and so on.
Mode=33206 indicates that the file is a file type, and mode=16822 indicates that the file is a folder
Synchronous version: fs.statSync (path)
8. Fs.watch (filename, [options], [listener])
Observe the change of the specified path. Filename can be a file or directory.
/ / listener is a listener, callback function, with two parameters: the event event and the name of the listening file filename
9. Fs.mkdir (path, [mode], callback) / / mode mode, read-only or read-write mode
Create a folder
Synchronous version: fs.mkdirSync (path, [mode])
10. Fs.readdir (path,callback)
Read folder
Synchronous version: fs.readdirSync (path)
The callback function includes two parameters, the err error message and all the files and folder information under the current folder fileList.
11. Fs.rmdir (path,callback)
Delete folder
Synchronous version: fs.rmdirSync (path)
Seventh, use node for web development
1. User's Internet access process
User input https://www.baidu.com/
Send a https request (similar to dialing a phone number) through a browser to request a baidu.com, which can be converted to an ip address
Through ip location, to a specified machine in the network, and then the machine will receive the request sent by the user, and then process the request and return the corresponding content.
In short:
The user sends a http request to the specified server through the browser
The server receives the request and analyzes and processes the request
After the server has finished processing, the corresponding data is returned to the user's machine.
The browser receives the data returned by the server and analyzes and processes it according to the received data.
Web development: the data exchange between two machines, the interaction between client and server.
The client sends a http request to the specified server-- > the server receives and processes the request-- > returns data to the client, which is compared to Thunderbolt download.
Http protocol:
To develop web, you must first deal with the process of receiving requests from the server, so to build a server, the server can receive links and requests from any client, and then process them accordingly
2. Http module
Let http = require ('http')
The server can be built by using this module.
Server.listen (); / / if no parameter is passed, the default system will automatically assign the port number, but it is not recommended to actively set the port number and hostname
Res.writeHead (200), {/ / 200. Ok is returned by default.
Content-type: 'text/html;charset=utf-8' / / will output the returned information to the page as html, and the html tag will work
Content-type: 'text/plain' / / will output the returned information to the page as a text file, and the html tag will not work
})
/ * * build a http server to handle http requests sent by users * you need to use node to provide a module http* / load a http module let http = require ('http'); / / create and return a web server object let server = http.createServer () through the createServer under the http module Server.on ('error', (err) = > {console.log (err)}) server.on (' listening', () = > {console.log ('linstening...')}) server.on (' request', (req,res) = > {/ / req is the data sent by the client, and res is the data returned by the server console.log ('requested by the client') / / console.log (req) / / req contains the request header, path information attached to the domain name / a/index.html, method method / / console.log (res); / / res includes the response body information (that is, the content displayed on the web page) and some information outside the body, such as the return message (not visible on the web page) res.writeHead ('200 content-type':'text/html) Charset=utf-8'}) / / res.write ('hello'); / / res.end (); / / can be merged into one-step res.end (' hello');}) server.listen (8080 recording localhost')
3. Url module
Let url = require ('url')
Url.parse (); / / is specially used to parse the url path and return data in json format
4. Use querystring module method to process the data submitted by get and post.
Let qs = require ('querystring')
Send data in get mode
Qs.parse ('foo=bar&abc=xyz&abc=123'); / / {foo:' bar',abc: ['xyz',' 123']}
Send data in post mode
Let http = require ('http'); let url = require (' url'); let fs = require ('fs'); let qs = require (' querystring'); let server = http.createServer (); let filename = _ _ dirname +'/ html/' Server.on ('error', (err) = > {console.log (err)}) server.on (' listening', () = > {console.log ('listening')}) server.on (' request', (req,res) = > {var urlStr = url.parse (req.url)) / / returns an object whose pathname attribute is the same as req.url. Switch (urlStr.pathname) {case'/': getData (filename+'index.html',req,res); break; case'/ user': getData (filename+'user.html',req,res); break Case'/ login': getData (filename+'login.html',req,res); break; case'/ login/check': / * console.log (req.method); / / get console.log (urlStr.query); / / username=xiaoxiao&password=1 console.log (qs.parse (urlStr.query)) / / [Object: null prototype] {username: 'xiaoxiao', password:' 1'} * / if (req.method.toUpperCase () = 'POST') {let str ='; req.on ('data', (chunk) = > {str + = chunk }) req.on ('end', () = > {console.log (str); / / username=13795232495&password=111 console.log (qs.parse (str)); / / [Object: null prototype] {username:' 13795232495, password: '111'})} break Default: break;}}) function getData (filename,req,res) {fs.readFile (filename, (err,data) = > {/ / console.log (data.toString ()); / / output all the tag contents in the page if (err) {res.writeHead (404). Charset=utf8'}) res.end ('404')} else {res.writeHead (200 content-type':'text/html;charset=utf8', {'content-type':'text/html;charset=utf8'}) res.end (data)})} server.listen (8082) / * * build a http server to handle http requests sent by users * you need to use node to provide a module http* / load a http module let http = require ('http'); let url = require (' url'); / / create and return a web server object let server = http.createServer () through createServer under the http module Server.on ('error', (err) = > {console.log (err)}) server.on (' listening', () = > {console.log ('linstening...')}) server.on (' request', (req,res) = > {/ / req is the data sent by the client, and res is the data returned by the server console.log ('requested by the client') console.log (req.url) / / req contains request header, path information attached to the domain name / a/index.html, method method / / console.log (res) / / res includes the response body information (that is, the content displayed on the web page) and some information outside the body, such as the return message (not visible on the web page) switch (req.url) {case'/': res.writeHead (200 content-type':'text/html) Charset=utf-8'}) res.end ('this is the home page'); break; case'/ user': res.writeHead (200 recordings, {'content-type':'text/html;charset=utf-8'}) res.end (' this is the user page'); break Default: res.writeHead (404 content-type':'text/html;charset=utf-8') res.end ('404); break;} / / res.write (' hello'); / / res.end () / / can be merged into one step / / res.end ('hello')}) server.listen (8080 recording localhost')
[note]:
1. Async means that a callback function will be executed after successful execution, and the following code will continue to execute, even if an error is reported, it will not hinder the execution of the following code; synchronization means continue to execute the following code if it is successful. If you report an error, it will be stuck here, and the following code will not be executed.
2. The so-called parameter filename, including the name and path of the file (if any), such as creating an index.html under the task folder
So, filename='task/index.html',
To include the name of the file, it cannot be just an empty path, 'task/'
These are all the contents of this article "what is the purpose of nodejs?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to 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.