node in action 讀書(shū)筆記

第一章

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的一種類(lèi)型 洞拨,詳細(xì)的請(qǐng)見(jiàn)列表

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.因?yàn)榧嫒菪缘膯?wèn)題,使用Socket.io會(huì)更可靠。

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 目錄遍歷攻擊

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末颠印,一起剝皮案震驚了整個(gè)濱河市昧诱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌潭辈,老刑警劉巖鸯屿,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件澈吨,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡寄摆,警方通過(guò)查閱死者的電腦和手機(jī)谅辣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)婶恼,“玉大人桑阶,你說(shuō)我怎么就攤上這事」窗睿” “怎么了蚣录?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)眷篇。 經(jīng)常有香客問(wèn)我萎河,道長(zhǎng),這世上最難降的妖魔是什么蕉饼? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任虐杯,我火速辦了婚禮,結(jié)果婚禮上椎椰,老公的妹妹穿的比我還像新娘厦幅。我一直安慰自己,他們只是感情好慨飘,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布确憨。 她就那樣靜靜地躺著,像睡著了一般瓤的。 火紅的嫁衣襯著肌膚如雪休弃。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,475評(píng)論 1 312
  • 那天圈膏,我揣著相機(jī)與錄音塔猾,去河邊找鬼。 笑死稽坤,一個(gè)胖子當(dāng)著我的面吹牛丈甸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播尿褪,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼睦擂,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了杖玲?” 一聲冷哼從身側(cè)響起顿仇,我...
    開(kāi)封第一講書(shū)人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后臼闻,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體鸿吆,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年述呐,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了惩淳。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡市埋,死狀恐怖黎泣,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情缤谎,我是刑警寧澤抒倚,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站坷澡,受9級(jí)特大地震影響托呕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜频敛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一项郊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧斟赚,春花似錦着降、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至发侵,卻和暖如春交掏,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背刃鳄。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工盅弛, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人叔锐。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓挪鹏,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親愉烙。 傳聞我的和親對(duì)象是個(gè)殘疾皇子狰住,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容