第一章
1.node定义:a platform built on Chrome's javascript runtime for easily building fast, scalable network applications.Node.js uses an event-driven,non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
2.node 使用 v8引擎。v8 直接把javascript 代码 编译成machine code。
3.Asynchronous and evented:the browser
node provides an event-driven(event loop) and asynchronous platform for server-side javascript.I/O is non-blocking(asynchronous I/O)
when I/O happens in the browser, it happens outside of the event loop(outside the main script execution) and then an "event" is emitted when the I/O is finished,which is handled by a function called callback.(except alert prompt confirm and synchronous XHR)
4.Asynchronous and evented: the server
Apache uses multi-threaded approach with blocking I/O
Nginx ,like node ,uses an event loop with asynchronous I/O
5.DIRT -data-intensive real-time .Node was built from the ground up to have an event-driven and asynchronous model.Node is a platform for javascript.
6.Node can build server ,just like Apache HTTP server which is hosted a PHP application)
//an example of an HTTP server that simply responds to any request with "hello world"
var http = require('http')
var server = http.createServer()
server.on('request',function(req,res){
res.writeHead(200,{'Content-Type','text/plain'})
res.end('hello world')
})
server.listen(3000)
console.log('Server running at http://localhost:3000')
7.node can use stream to handle data.Node provide readable and writeable stream to bring and send data in chunk by chunk.The readable and writable streams can be connected to make pipes,much like you can do with the | (pipe) operator in shell scripting.This provides an efficient way to write out data as soon as it's ready, without waiting for the complete resource to be read and then written out.
//This example illustrate streaming an image to a client
var http = require('http')
var fs = require('fs')
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'image/png'})
fs.createReadStream('./image.png').pipe(res)
}).listen(3000)
console.log('Server running at http://localhost:3000')
第二章
1.MIME:Multipurpose Internet Mail Extensions is an Internet standard that extends the format of email to support...In HTTP,servers insert the MIME at the beginning of any web transmission.Clients use this content type or media type header to select an appropriate "player" for the type of data the header indicates.
Content-Type:text/plain 中 text/plain 就是MIME的一种类型 ,详细的请见列表
2.WebSocket:WebSocket is a computer communications protocol,providing full-duplex(双向) communication channels over a single TCP connection.Data transfer is real-time.This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for massages to be passed back and forth while keeping the connecting open.The communication are done over TCP port number 80.因为兼容性的问题,使用Socket.io会更可靠。
3.聊天室交互模型
Node can easily handle simultaneously serving HTTP and WebSocket using a single TCP/IP port.
4.application dependency :is a module that need to be installed to provide functionality needed by the application.
5.Although you can create Node applications without formally specifying dependencies, it's a good habit to take the time to specify them.Application dependencies are specified using a package.json file.This file is always placed in an application's root file.
6.package.json :In a package.json file you can specify many things, but the most important are the name of your application, the version ,a description of what the application does, and the application's dependencies.
{
"name":"chatrooms",
"version":"0.0.1",
"description":"Minimalist multiroom chat server",
"dependencies":{
"socket.io":"~0.9.6",
"mime":"~1.2.7"
}
}
Npm can read dependencies from package.json files and install each of them with a single command : npm install
7.Accessing memory storage(RAM) is faster than accessing the filesystem.Because of this, it's common for Node applications to cache frequently used data in memory.
function serveStatic(response,cache,absPath){
if(cache[absPath]){
sendFile(response,absPath,cache[absPath]);
}else{
fs.exists(absPath,function(exists){
if(exists){
fs.readFile(absPath,function(err,data){
if(err){
send404(response)
}else{
cache[absPath] = data;
sendFile(response,absPath,data)
}
})
}
})
}
}
- A running server can be stopped by using Ctrl-C on the command line.
9.In chatroom, Socket.IO provides virtual channel. So instead of broadcasting every message to every connected user, you can broadcast only to those who have subscribed to a specific channel.
10.Event emitter
In node.js an event can be described simply as a string with a corresponding callback. An event can be "emitted" (or in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted.
第三章
- Node modules allow you to select what functions and variables from the included file are exposed to the application.If the module is returning more than one function or variable, the module can specify these by setting the properties of an object called
exports
.If the module is returning a single function or variable, the propertymodule.exports
can instead be set.
2.By avoiding pollution of the global scope,Node's module system avoids naming conficts and simplifies code reuse.Modules can then be published to the npm(Node Package Manager) repository, an online collection of ready-to-use Node modules , and shared with the Node community without those using the modules having to worry about one module overwriting the variables and functions of another.
3.Modules can either be single files or directories containing one or more files.If a module is a directory, the file in the module directory that will be evaluated is normally named index.js. To create a typical module, you create a file that defines properties on the exports
object with any kind of data ,such as strings, objects, and functions.
4.The variable in modules which does not in exports
object can affects the logic of function in exports
but can't be directly accessed by the application.
5.require
is one of the few synchronous I/O operation available in Node.when requiring, the .js
extension is assumed, so you can omit it if desired.
6.what really gets exported
What ultimately gets exported in your application is
module.exports
.exports
is set up simply as a global reference tomodule.exports
, which initially is defined as an empty object that you can add properties to. Soexports.myFunc
is just shorthand formodule.exports.myFunc
.
As a result , ifexports
is set to anything else, it breaks the reference betweenmodule.exports
andexports
. Becausemodule.exports
is what really gets exported,exports
will no longer work as expected --it doesn't referencemodule.exports
anymore. If you want maintain that link, you can makemodule.exports
referenceexports
again as follows:
module.exports = exports = Currency
If you create a module that populates both exports
and module.exports
,module.exports
will be returned and exports
will be ignored
- Node includes a unique mechanism for code reuse that allows modules to be required without knowing their location in the filesystem.if you omit the '/' or '../' or './' ,the rules as follows:
The NODE_PATH
environmental variable provides a way to specify alternative location for Node modules. If used , NODE_PATH
should be set to a list of directories separated by semicolons in Windows or colons in other operating systems.
- The
package.json
file ,when placed in a module directory ,allows you to define your module using a file other than index.js.
9.The other things to be aware of is Node's ability to cache modules as Object. If two files in an application require the same module, the first require will store the data returned in application memory so the second require will , in fact have the opportunity to alter the cached data.
10.Two popular models in the Node world for managing response logic:
1.callback,which generally define logic for one-off responses, is a function that passed as an
argument to an asynchronous function, that describes what to do after the asynchronous operation has completed.
2.Event listeners, on the other hand ,are essentially callbacks that are associated with a conceptual entity(an event).
11.events
var EventEmitter = require('events').EventEmitter;
var channel = new EventEmitter();
channel.on('join',function(){
console.log('Welcome');
});
All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.
When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and will be discarded.
If an EventEmitter does not have at least one listener registered for the 'error' event, and an 'error' event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.
As a best practice, listeners should always be added for the 'error' events.
const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
console.log('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error
12.inherit
,which is part of Node's built-in util module . The inherit
function provide s a clean way to inherit another object's behavior.
var events = require('events'),util = require('util');
util.inherits(Watcher,events.EventEmitter);
// is equivalent to
Watcher.prototype = new events.EventEmiiter();
13.Node's event loop , for example, keeps track of asynchronous logic that hasn't completed processing.As long as there's uncompleted asynchrounous logic, the Node process won't exit.
14.you can use closure to control your application state.
15.flow control : the concept of sequencing groups of asynchronous tasks is called flow control
by th Node community. There are two types of flow control :serial
and parallel
.
i.serial
ii.parallel
第四章
1.At Node's core is a powerful streaming HTTP parser consisting of roughly 1500 lines of optimized C, written by the author of Node, Ryan Dahl. This parser , in combination with the low-level TCP API that Node exposes to Javascript, provides you with a very low-level, but very flexfible, HTTP server.
2.create HTTP server
var http = require('http');
var server = http.createServer(function(req,res){
//handle request
})
For every HTTP request received by the server, the request callback function will be invoked with new
req
andres
objects. Prior to the callback being triggered, Node will parse the request up through the HTTP headers and provide them as part ofreq
object. But Node doesn't start parsing the body of the request until the callback has been fired. This is different from some server-side frameworks, like PHP,where both the headers and the body of the request are parsed before your application logic runs.
Node will not automatically write any response back to the client. After the request callback is triggered , it's your responsibility to end the response using theres.end()
method. This allows you to run any asynchronous logic you want during the lifetime of the request before ending the response. If you fail to end the response, the request will hang until the client times out or it will just remain open.
3 . Alter the header fields of an HTTP response
i. res.setHeader(field,value);
ii. res.getHeader(field)
iii.res.removeHeader(field)
For example, you'll have to send a
Content-Type
header with a value oftext/html
when you're sending HTML content so that the browser knows to render the result as HTML.
var body = 'Hello World';
res.setHeader('Content-Length',body.length);
res.setHeader('Conent-Type','text/plain');
res.statusCode = 302;
res.end(body);
You can add and remove headers in any order, buy only up to the firstres.write()
or res.end
call (res.statusCode as well).
Status Code Definitions
CRUD --create read update delete.(http verbs)
RESTful web service -- a service that utilizes the HTTP method verbs to expose a concise API.
cURL -- a powerful command-line HTTP client that can be used to send requests to a target server.
REPL -- read-eval-print-loop ,run node from command without any arguments then you will find ...
5.example
6.node url
module, the requested URL can be accessed with the req.url
property.