Last active
March 19, 2018 08:37
-
-
Save Gyumeijie/2f26e8971320ea873cc4b262dbf60b56 to your computer and use it in GitHub Desktop.
node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 1. 为什么JavaScript是单线程? ---为什么不是多线程呢 | |
| JavaScript的单线程,与它的用途有关。作为浏览器脚本语言,JavaScript的主要用途是与用户互动, | |
| 以及操作DOM。这决定了它只能是单线程,否则会带来很复杂的同步问题。 | |
| 如果排队是因为计算量大,CPU忙不过来,倒也算了,但是很多时候CPU是闲着的,因为IO设备(输入输出设备) | |
| 很慢(比如Ajax操作从网络读取数据),不得不等着结果出来,再往下执行。 | |
| JavaScript语言的设计者意识到,这时主线程完全可以不管IO设备,挂起处于等待中的任务,先运行排在后面的任务。 | |
| 等到IO设备返回了结果,再回过头,把挂起的任务继续执行下去。 | |
| 为了利用多核CPU的计算能力,HTML5提出Web Worker标准,允许JavaScript脚本创建多个线程, | |
| 但是子线程完全受主线程控制,且不得操作DOM。所以,这个新标准并没有改变JavaScript单线程的本质。 | |
| 2. 异步执行的运行机制如下: | |
| (1)所有同步任务都在主线程上执行,形成一个执行栈(execution context stack)。 | |
| (2)主线程之外,还存在一个"任务队列"(task queue)。只要异步任务有了运行结果,就在"任务队列"之中放置一个事件。 | |
| (3)一旦"执行栈"中的所有同步任务执行完毕,系统就会读取"任务队列",看看里面有哪些事件。那些对应的异步任务, | |
| 于是结束等待状态,进入执行栈,开始执行。 | |
| (4)主线程不断重复上面的第三步。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 1. 中间件之间使用的request和respond对象是共享的以及可变的, 因此我们可以先对request对象进行部分处理以便于后面中间件对 | |
| request对象的处理 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Nodejs的模块系统是基于文件的: | |
| 1. 每个文件都是一个模块 | |
| 2. 每个文件可以通过module这个变量来访问当前模块的定义,下面是module对象的一个例子: | |
| Module { | |
| id: '.', | |
| exports: {}, | |
| parent: null, | |
| filename: '', | |
| loaded: false, | |
| children: [], | |
| paths: [ ] | |
| } | |
| 3. 为了导出当前模块中的变量或函数,则需要使用modeule.exports变量,也可以使用简单的exports别名 | |
| 4. 为了导入一个模块需要使用全局的require函数 | |
| 使用require导入一个文件时,不要使用.js后缀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 1. request 实现了readable stream接口, respond实现了writable stream接口 | |
| 2. pipe表示流已经结束,request.pipe(respond), 后面不能在写入数据和使用respond.end("data") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment