node in action 读书笔记

第一章

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.聊天室交互模型

WechatIMG134.jpeg

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)
                    }
                })
            }
        })
    }
}
  1. 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.


第三章
  1. 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 property module.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 . exportsis set up simply as a global reference to module.exports, which initially is defined as an empty object that you can add properties to. So exports.myFunc is just shorthand for module.exports.myFunc.
As a result , if exports is set to anything else, it breaks the reference between module.exports and exports. Because module.exports is what really gets exported,exports will no longer work as expected --it doesn't reference module.exports anymore. If you want maintain that link, you can make module.exports reference exports 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

  1. 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:
WechatIMG60.jpeg

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.

  1. The package.jsonfile ,when placed in a module directory ,allows you to define your module using a file other than index.js.
WechatIMG62_02.jpg

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 inheritfunction 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.

WechatIMG76.jpeg

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.

WechatIMG78.jpeg

i.serial

WechatIMG79.jpeg

WechatIMG80.jpeg

WechatIMG81.jpeg

ii.parallel

WechatIMG82.jpeg
WechatIMG83.jpeg

第四章

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 and res objects. Prior to the callback being triggered, Node will parse the request up through the HTTP headers and provide them as part of req 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 the res.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 of text/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


WechatIMG98.jpeg

6.node url module, the requested URL can be accessed with the req.url property.

WechatIMG99.jpeg

7.directory traversal attack 目录遍历攻击

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容