background knowledge
node.js founder Ryan Dahl. 2009.2 create a Web server and provide a library in your blog for the first time. The initial version was released in GitHub in May.
event driven
After registering an event, wait for the event to trigger execution without relying on its own order of occurrence. With limited resources, the system can complete certain tasks without waiting for other resources.
Outstanding performance
Run in single process and single thread mode.
Single thread
This means that the main thread is "single thread". All blocked parts are handed over to a thread pool for processing, and then the main thread cooperates with the thread pool through a queue.
Asynchronous, non blocking I/O
For example, many functions such as file operation are executed asynchronously,
Issue I/O call; Execute callback
Note: nodejs is weak in processing CPU intensive applications, template rendering, compression, decompression, encryption, decryption and other operations
nodeJS content
nodeJS comes with repl (Interactive running environment), which can also be tried on the browser.
console
console.dir() inputs an object to the console
console.time() ; console.timeEnd() enter the running time of the code
console.trace() outputs the current position stack information.
Package management
npm init
Can generate a package JSON file is the description file of the whole project. Through this file, you can clearly understand the package dependency, version and other information of the project.
Direct command: npm init -y or npm init --yes
npm i < package name >
– save or - S can be placed in the dependencies field
If you continue to add - dev, it will be in the devDependencies field in the development stage
It is recommended to record all project installation packages in package In the JSON file, we only need to execute npm i when we use it, and npm uninstall when we don't need it.
Core module
http module
Create Http server and client
url module
url address processing
url.parse(): parse a URL address and return a URL object
url.fomate(urlObj): accept a URL object as a parameter and return a complete URL address
url.resolve(from,to) accepts a base url object and a href url object, parses them like a browser, and returns the full address.
querystring module
Query string processing
querystring.parse(): similar to JSON parse()
querystring.stringify(): similar to JSON stringify();
Common modules
util module
util.inspect(): returns a string formed by deserialization of an object
util.format(): returns a string formatted with a placeholder
util.log(): similar to console log().
path module
Path processing
path.join(): connect all parameters and return a path
path.extname(): returns the extended name of the path parameter. If not, an empty string is returned
path.parse(): resolves the path to a path object
path.format(): accept a path object parameter and return a complete path address.
dns module
dns.resolve(): resolves a domain name into an array of the specified type
dns.lookup(): returns the address of the first discovered IPv4 or IPv6.
dns.reverse(): resolve the domain name through IP.
File world
Open file
fs.open(path,flags[,mode],callback)
flag value | explain |
---|---|
r | Open the file in read mode and throw an exception if the file does not exist |
r+ | Open the file in read-write mode and throw an exception if the file does not exist |
rs | Read files synchronously |
rs+ | Read and write files synchronously |
w | Open the file in write mode and create it if the file does not exist |
wx | Similar w, but if the file path exists, the file write fails |
w+ | Open the file in read-write mode and create it if the file does not exist |
wx+ | Similar to w +, but the file path exists, the file reading and writing fails |
a | Open the file in append mode and create if the file does not exist |
ax | Similar to a, but if the file path exists, the append fails |
Close file
fs.close(fd,callback)
read file
fs.read()
fs.readFile()
write file
fs.writeFile()
fs.appendFile();
Other file operations (csv, xml, json)
1. Download first (npm i csv)
2. Parsing and generating csv files
3. Convert csv file to txt file
At present, nodeJS does not support Chinese codes such as GBK or GB2312, and third-party modules need to be introduced (iconv or iconv Lite; iconv only supports Linux)
Currently supported: utf-8, ucs2, ascii, binary, base64, hex
Network world
TCP server
net module is used.
net.createServer()
let net = require('net'); let server = net.createServer((socket)=>{ conosle.log('someone connect'); })
Listen for client connections
server.listen()
server.listen(8888,()=>{ console.log('server is listening'); })
Manual listening writing method
server.listen(8888); server.on('listening',()=>{ console.log('server is listening'); })
To use Win's Telnet, use the command: open localhost 8888
Besides listening, there are also connection, close and error events.
View service listening address
server.address()
There are three attributes: port, family and address
Number of clients connected to the server
server.getConnections(err,count);
server.maxConnections = 3; server.getConnections((err,count)=>{ console.log(count); })
Get the data sent by the client
Listen for data events
server.on('data',()=>{ console.log(data.toString()); })
In addition to data events, socket objects also have connect, end, error, timeout and other events.
Send data to client
Using socket write(data,encode)
The first parameter is data, the second is coding format (optional), and there can be callback function.
socket.write(data,()=>{ let writeSize = socket.bytesWritten; }) socket.on('data',()=>{ let readSize = socket.bytesRead; console.log(readSize); })
In addition to the byteswriten and bytesRead sending and receiving bytes attributes, the socket object also has localport (address of local port), lacalAddress (local IP address), remote Port (remote Port address), remoteFamily (remote IP protocol family) and remoteAddress (remote IP address).
TCP customer service terminal
Create client
let net = require('net') let client = new net.Socket(obj);
obj includes: FD (specify an existing file descriptor, null by default); Readable (whether to allow reading on this socket, false by default); Writeable (...); Allowhalfopen (whether to ask the server to send back a fin package, false/true).
Connect to tTCP server
let client = net.Socket(); client.connect(8888,'127.0.0.1',()=>{ console.log('connect the server'); })
Get data sent from TCP server
client.connect(8888,'127.0.0.1',()=>{ console.log('connect the server'); }) client.on('data',(data)=>{ console.log(data) })
Send data to TCP server
client.connect(8888,'127.0.0.1',()=>{ client.write('message from client');//Data sent })
HTTP server
Create HTTP server
let http = require('http'); let server = http.createServer((req,res)=>{ res.writeHead(200,{ 'content-type':'text/plain' }); res.end('hello,nodeJS'); }) server.listen(8888,()=>{ console.log('listening port 8888'); })
Columns:
//Read html file let server = http.createServer((req,res)=>{ res.writeHead(200,{ 'content-type':'text/html' }) let data = fs.readFileSync('./index.html'); res.write(data); res.end(); })
Content type is used to indicate the type of data transmitted by the client or server, which is used for corresponding analysis; If it is the original value, the index will be displayed directly on the page HTML code
Routing control
//Handle html, js, css, and images module.exports = { '.html':'text/html', '.css':'text/css', '.js':'text/javascript', '.gif':'image/gif', '.ico':'image/x-icon', '.jpeg':'image/jpeg', '.jpg':'image/jpeg', '.png':'image/png' }
Routing control return file
let server = http.createServer((req,res)=>{ let filePath = '.' + url.parse(req.url).pathname; if(filePath === './'){ filePath = './index.html'; } //Determine whether the corresponding file exists fs.exists(filePath,(exist)=>{ if(exist){ let data = fs.readFileSync(filePath); let contentType = mine[path.extname(filePath)]; res.writeHead(200,{ 'content-type':contentType }) res.write(data); res.end(); }else{ res.end('404'); } }) })
UDP server
let dgram = require('dgram'); //Create UDP server let socket = dgram.createSocket('udp4');
socket objects in UDP mainly have the following methods:
bind(): binding port number
send(): send data
address(): get the address information related to the socket port number object
close(): close the socket object
Database ocean
Using MongoDB
Use mongoose to connect to mongDB:npm i mongoose
Connect mongodb using node mongodb native: NPM I mongodb
See mongodb for details
Connect to MySQl
Preparation: npm i mysql
const mysql = require('mysql'); const connection = mysql.createConnection({ host:'localhost', port:3306, user:'root', password:'123456', database:'homedata' })
End connection
connection.end(()=>{}) //You can also use the destroy () method, which will immediately terminate the underlying socket without triggering more events and callback functions. connection.destory()
The mysql module provides a query() method, which can be used to execute sql statements to operate the mysql database.
connection.query('select * from data',(err,rows)=>{})
connection. The query () method also has an optional paramInfo parameter. When the sql statement contains variables, you can set "?" It is placed in the sql statement as a placeholder and passed to the sql statement through the paramInfo parameter.
connection.query('select * from ?',[table],(err,rows)=>{})
mysql module also provides an escape() method to prevent sql injection attacks.
//Define sql statement let sql = 'select * from users where userid=123'+connection.escape(userid); connection.query(sql,(err,rows)=>{})