Original digest self of front-end blog, welcome everyone to visit
http://www.hacke2.cn
Chapter II JS overview based on GOOGLEV8 engine
- Object.keys (o)
- Array methods: Traversing foreach, filtering filter, changing map
- Implements the String.prototype.trim ()
- Contains JSON parsing
Chapter III blocking and non-blocking IO single-threaded attention points
- Careful handling of in-memory variables may affect the results of two visits
- Do not write blocking code that may affect the time of a second visit
Event rotation
- Register Events First
- Keep asking if these events have been distributed dispatch
- When the event is distributed, the corresponding callback is triggered
- If the event does not fire, continue to execute other code
- It is not possible to catch exceptions thrown by functions that will be executed in the future.
- Avoid synchronizing IO
The Javascriptglobal object in the fourth chapter Nodez
- Corresponds to browser window
Process Object
- Process.nexttick = = Sertimeout (fn,1)
Module
- Require module exports
- Npm
- The absolute module refers to the node built-in module as well as the Node_modules module require (' FS ')
- Relative module refers to the module require ('./module ') found through a relative path
- Burst data EXPORTS.A (multiple), rewrite Module.exports (one)
# #事件
- Eventemitter
- Event listener on, event distribution emit, event removal RemoveListener
- Execute only once once
- The data event is partially arrived at, instead of a one-time full arrival return to you
Buffer
Fifth Chapter CLI &fs Apistream
- stdin readable stream Stdout/stderr writable stream
- Stdin.resume Waiting for user input
- console = = process.stdout.write (str + ' \ n ')
Fs
- Readdirsync (__dirname) readfilesync sync
- Readdir ('. ', async) readFile Async
- Createreadsteam read variable size has data, end events are used for pictures, large files, etc.
- Watchfile Monitor file changes
Process
- Parameters for PROCESS.ARGV operation
- PROCESS.CWD getting the current working directory
- PROCESS.ENV Environment variables
- Process.exit exit
- Signal Volume
Sixth Chapter TCPTCP
- Connection-oriented, IP-based protocol
- The IP protocol is out of order, TCP sends the IP containing the identifier and the data flow sequence information
- byte-oriented character and character encoding are completely ignorant, good flexibility
- Reliability three times handshake, window time re-hair
- Flow control, speed control for receiving and transmitting
- Congestion control to avoid congestion, the delay rate and packet loss rate will not be too high
Telnet
- When not the Telnet protocol is automatically downgraded to TCP
- Send get/http/1.1 Analog browser request, two times enter
Net
- node. JS Core TCP Module
- Data Close End Event
- Conn.setencoding (' Utf-8 ') or buffer.tostring (' Utf-8 ')
- Server-side Createserver client Connect method connect event
Seventh Chapter Httphttp
- TCP upper Layer protocol
- Content-type type text, HTML, XML, JSON, PNG
- The content length of the transfer-encoding:chunked output cannot be determined, and node's innate asynchronous mechanism can be formed accordingly.
- 301 Permanent Transfer 302 temporary transfer 304 resource not changed 403 unauthorized 404 Resource Not Found
- Form Content-type application/x-www-form-unencoded
HTTP Module
- Request, Response parameters
- To determine the route to Method+url
- QueryString module parses a string into an object
- The request method simulates a demand, passes back the data 2 binary, sets the Utf-8
- superagent Analog Client (impersonate a request) module
- Up Reboot Server module
Eighth Chapter Connect Toolset & Middleware
- Module: Connect
- Middleware Call Server.user (...)
- Log middleware Console.log ('%s%s ', Req.method, Req.url)
- Analog request time too long middleware, in Res.end is to clear the timer
- Static middleware to handle connect.static (' ... ')
- Query middleware Gets the queries string connect.query
- Logger middleware connect.logger (' Dev ')
- Body Parser Middleware Connect.bodyparser () if the JSON format is used in post, the body parser automatically goes to the JSON object, and the user uploads the file req.body.file multi-file form name using Name= "File[]"
- Seesion Middleware Session Connect.session use method Req.session.user
- Redis Session Persistence Middleware
- Methodoverride Middleware enables low-version browsers to support put, DELETE, PATCH
- BasicAuth Middleware user authentication
Nineth Chapter Expressexpress
- Web application Development Framework, based on Connect
- App.set (' View engine ', ' Ejs ') set up the Ejs template engine
- App.set (' View ', __dirname + '/view ') set the view layer path
- App.set (' View cache ', ' true ') sets the template cache
- Use App.get (), App.put (), app.post () to configure routing, pass parameters such as: ID, get req.params.id
- Res.render (' Search ', obj) render template
- Other settings case sensitive, strict routing, JSONP callback
- Provides a quick way for res and req render rendering, redirect redirection Req.header check header information
- Middleware App.user (function (req, res, next) {})
- Code organization layering, subcontracting, MVC, recommendations modeled after spring MVC
Template engine
Express/haml/jade/coffeekup/jquery Templates for node
#第十章WebSocket
Ajax
- Asynchronous javascripy
- An HTTP request, consumes network resources, and is not suitable for real-time service HTML5 WebSocket
- Based on WS-Protocol
- Node Support: Websocket.io
- Client New WebSocket
Defects
- Off does not mean disconnection, use heartbeat detection mechanism to determine
- Not friendly to JSON support
- Client temporary disconnect cannot resolve using timer or refresh page?
- Compatibility
11th Chapter Socket.io Advantage
- Cross-browser, support WebSocket is native, does not support the use of long connection, the connection will continue to open 20-50s
- Even if the browser-supported WebSocket is banned by the proxy or firewall, Socket.io will still use other technologies to resolve
- If the client stops transmitting information and does not shut down properly for a certain time, the connection is considered to be disconnected
- Auto-Reconnect when connection is lost
- Hierarchy of logic, with namespaces
- supports emit distribution and listen monitoring events
12th Chapter Mongodbmongodb
- Document oriented, the vast majority of cases are JSON
- Connect to New MongoDB. Server (' 127.0.0.1 ', 27017)
- API Open Insert Find Ensureindex FindOne
- $set setting $push push-in array
Mongoose
- Similar to the ORM framework in Java, simplifying database development
- Connection Mongoose.connect (' Mongodb://localhost/database ')
- Schema: A database model skeleton stored as a file, not capable of database operation
- Model: Generated by schema Publishing, database operations with abstract properties and behavior
- Entity: Entities created by model, his actions also affect the database
- Index Index title: {type:string, index:true} unique:true unique
- New Schema ({}). Pre (' Save ', function () {}) do some processing before saving
- Common API Find,findone,remove,update,count
- New Schema ({}). Find ({_id: ' xx '}). where (' title ', ' xxx '). Sort (' content ',-1). Limit (5). Run (function (err, data) {}) Similar JQ query
- . Select (' _id ', ' name ') Choose query specified field
- . Skip skips Mongoose. Schema.objectid Generating Random IDs
- Clazz: [clazz] Nested Sehema
- Clazz: {type:objectid, ref: ' Clazz '} Associated query
- Add static PersonSchema.statics.findByName via model call
- Add instance method PersonSchema.methods.findSimilarTypes entity call
13th Chapter Mysqlmysql
- Use query to execute SQL primarily
- have placeholders? Insert data (same as Java)
- Using the Seqelize node version ORM Framework
14th Chapter Redisredis
- Application scenario: Simple data model, data set. Suitable for storage in memory
- Seesion Persistence
15th. Code Share writing compatibility code
- Export module with front-end backend available
(function (module) {
Module.exports = function (A, b) {
return a+b;
}
If (' undefined '! = typeof window) {
Window.add = Module.exports;
}
}) (' undefined ' = = typeof module? {module: {exports: {}}}: module)
- To implement the ECMA: Extend a prototype or implement a tool function
- Eventemitter. Assert, XMLHttpRequest, DOM, WebSocket, Node-canvas are all implemented on Git
- Bowserbuild node module to browser-aware code
16th. Test assert
- Common API Ok,be/equal/eql/a/macth ...
Mocha
- Simplified writing
- Testing asynchronous code
- Generate reports
Great node. js Reading notes