├── LICENSE └── README.md /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Chenng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 最近读《重学前端》,开篇就是让你拥有自己的知识体系图谱,后续学的东西补充到相应的模块,既可以加深对原有知识的理解,又可以强化记忆,很不错的学习方案。 4 | 5 | 这篇文章主要知识点来自: 6 | 7 | - [《Node.js硬实战:115个核心技巧》](https://www.amazon.cn/dp/B01MYX8XG1) 8 | - [i0natan/nodebestpractices](https://github.com/i0natan/nodebestpractices) 9 | - 后续学习的一些知识点 10 | 11 | 12 | 13 | # docsify 文档 14 | 15 | 16 | 17 | # 更新记录 18 | 19 | [CHANGE LOG](https://github.com/ringcrl/node-point/commits/master) 20 | 21 | # 说明 22 | 23 | 比较好的 markdown 的查看方式是直接用 VSCode 打开大纲,这样整个脉络一目了然,后续补充知识点也很快定位到相应的位置: 24 | 25 | ![01.png](https://qiniu.chenng.cn/2019-01-28-09-44-31.png) 26 | 27 | 这个 markdown 文件已经丢到 Github,有更新会直接推这里: 28 | 29 | https://github.com/ringcrl/node-point 30 | 31 | 博客上也会记录一些好玩的东西: 32 | 33 | www.chenng.cn/archives/ 34 | 35 | # 安装 36 | 37 | ```sh 38 | # 使用 nvm 安装 39 | https://github.com/creationix/nvm#install-script # Git install 40 | 41 | nvm install 42 | nvm alias default 43 | 44 | # 卸载 pkg 安装版 45 | sudo rm -rf /usr/local/{bin/{node,npm},lib/node_modules/npm,lib/node,share/man/*/node.*} 46 | ``` 47 | 48 | # 全局变量 49 | 50 | ## require(id) 51 | 52 | - 内建模块直接从内存加载 53 | - 文件模块通过文件查找定位到文件 54 | - 包通过 package.json 里面的 main 字段查找入口文件 55 | 56 | ### module.exports 57 | 58 | ```js 59 | // 通过如下模块包装得到 60 | (funciton (exports, require, module, __filename, __dirname) { // 包装头 61 | 62 | }); // 包装尾 63 | ``` 64 | 65 | ### JSON 文件 66 | 67 | - 通过 `fs.readFileSync()` 加载 68 | - 通过 `JSON.parse()` 解析 69 | 70 | ### 加载大文件 71 | 72 | - require 成功后会缓存文件 73 | - 大量使用会导致大量数据驻留在内存中,导致 GC 频分和内存泄露 74 | 75 | ## module.exports 和 exports 76 | 77 | ### 执行时 78 | 79 | ```js 80 | (funciton(exports, require, module, __filename, __dirname) { // 包装头 81 | console.log('hello world!') // 原始文件 82 | }); // 包装尾 83 | ``` 84 | 85 | ### exports 86 | 87 | - exports 是 module 的属性,默认情况是空对象 88 | - require 一个模块实际得到的是该模块的 exports 属性 89 | - exports.xxx 导出具有多个属性的对象 90 | - module.exports = xxx 导出一个对象 91 | 92 | ### 使用 93 | 94 | ```js 95 | // module-2.js 96 | exports.method = function() { 97 | return 'Hello'; 98 | }; 99 | 100 | exports.method2 = function() { 101 | return 'Hello again'; 102 | }; 103 | 104 | // module-1.js 105 | const module2 = require('./module-2'); 106 | console.log(module2.method()); // Hello 107 | console.log(module2.method2()); // Hello again 108 | ``` 109 | 110 | ## 路径变量 111 | 112 | ```js 113 | console.log('__dirname:', __dirname); // 文件夹 114 | console.log('__filename:', __filename); // 文件 115 | 116 | path.join(__dirname, 'views', 'view.html'); // 如果不希望自己手动处理 / 的问题,使用 path.join 117 | 118 | // HOME 目录 119 | const homeDir = require('os').homedir(); 120 | ``` 121 | 122 | ## console 123 | 124 | | 占位符 | 类型 | 例子 | 125 | | :----: | :----: | :---------------------------------: | 126 | | %s | String | console.log('%s', 'value') | 127 | | %d | Number | console.log('%d', 3.14) | 128 | | %j | JSON | console.log('%j', {name: 'Chenng'}) | 129 | 130 | ## process 131 | 132 | ### 查看 PATH 133 | 134 | ```js 135 | node 136 | 137 | console.log(process.env.PATH.split(':').join('\n')); 138 | ``` 139 | 140 | ### 设置 PATH 141 | 142 | ```js 143 | process.env.PATH += ':/a_new_path_to_executables'; 144 | ``` 145 | 146 | ### 获取信息 147 | 148 | ```js 149 | // 获取平台信息 150 | process.arch // x64 151 | process.platform // darwin 152 | 153 | // 获取内存使用情况 154 | process.memoryUsage(); 155 | 156 | // 获取命令行参数 157 | process.argv 158 | ``` 159 | 160 | ### nextTick 161 | 162 | process.nextTick 方法允许你把一个回调放在下一次时间轮询队列的头上,这意味着可以用来延迟执行,结果是比 setTimeout 更有效率。 163 | 164 | ```js 165 | const EventEmitter = require('events').EventEmitter; 166 | 167 | function complexOperations() { 168 | const events = new EventEmitter(); 169 | 170 | process.nextTick(function () { 171 | events.emit('success'); 172 | }); 173 | 174 | return events; 175 | } 176 | 177 | complexOperations().on('success', function () { 178 | console.log('success!'); 179 | }); 180 | ``` 181 | 182 | # Buffer 183 | 184 | 如果没有提供编码格式,文件操作以及很多网络操作就会将数据作为 Buffer 类型返回。 185 | 186 | ## toString 187 | 188 | 默认转为 `UTF-8` 格式,还支持 `ascii`、`base64` 等。 189 | 190 | ## data URI 191 | 192 | ```js 193 | // 生成 data URI 194 | const fs = require('fs'); 195 | const mime = 'image/png'; 196 | const encoding = 'base64'; 197 | const base64Data = fs.readFileSync(`${__dirname}/monkey.png`).toString(encoding); 198 | const uri = `data:${mime};${encoding},${base64Data}`; 199 | console.log(uri); 200 | 201 | // data URI 转文件 202 | const fs = require('fs'); 203 | const uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...'; 204 | const base64Data = uri.split(',')[1]; 205 | const buf = Buffer(base64Data, 'base64'); 206 | fs.writeFileSync(`${__dirname}/secondmonkey.png`, buf); 207 | ``` 208 | 209 | # events 210 | 211 | ```js 212 | const EventEmitter = require('events').EventEmitter; 213 | 214 | const AudioDevice = { 215 | play: function (track) { 216 | console.log('play', track); 217 | }, 218 | stop: function () { 219 | console.log('stop'); 220 | }, 221 | }; 222 | 223 | class MusicPlayer extends EventEmitter { 224 | constructor() { 225 | super(); 226 | this.playing = false; 227 | } 228 | } 229 | 230 | const musicPlayer = new MusicPlayer(); 231 | musicPlayer.on('play', function (track) { 232 | this.playing = true; 233 | AudioDevice.play(track); 234 | }); 235 | musicPlayer.on('stop', function () { 236 | this.playing = false; 237 | AudioDevice.stop(); 238 | }); 239 | 240 | musicPlayer.emit('play', 'The Roots - The Fire'); 241 | setTimeout(function () { 242 | musicPlayer.emit('stop'); 243 | }, 1000); 244 | 245 | // 处理异常 246 | // EventEmitter 实例发生错误会发出一个 error 事件 247 | // 如果没有监听器,默认动作是打印一个堆栈并退出程序 248 | musicPlayer.on('error', function (err) { 249 | console.err('Error:', err); 250 | }); 251 | ``` 252 | 253 | # util 254 | 255 | ## promisify 256 | 257 | ```js 258 | const util = require('util'); 259 | const fs = require('fs'); 260 | const readAsync = util.promisify(fs.readFile); 261 | 262 | async function init() { 263 | try { 264 | let data = await readAsync('./package.json'); 265 | 266 | data =JSON.parse(data); 267 | 268 | console.log(data.name); 269 | } catch (err) { 270 | console.log(err); 271 | } 272 | } 273 | ``` 274 | 275 | # 流 276 | 277 | ## 理解流 278 | 279 | 流是基于事件的 API,用于管理和处理数据。 280 | 281 | - 流是能够读写的 282 | - 是基于事件实现的一个实例 283 | 284 | 理解流的最好方式就是想象一下没有流的时候怎么处理数据: 285 | 286 | - `fs.readFileSync` 同步读取文件,程序会阻塞,所有数据被读到内存 287 | - `fs.readFile` 阻止程序阻塞,但仍会将文件所有数据读取到内存中 288 | - 希望少内存读取大文件,读取一个数据块到内存处理完再去索取更多的数据 289 | 290 | ### 流的类型 291 | 292 | - 内置:许多核心模块都实现了流接口,如 `fs.createReadStream` 293 | - HTTP:处理网络技术的流 294 | - 解释器:第三方模块 XML、JSON 解释器 295 | - 浏览器:Node 流可以被拓展使用在浏览器 296 | - Audio:流接口的声音模块 297 | - RPC(远程调用):通过网络发送流是进程间通信的有效方式 298 | - 测试:使用流的测试库 299 | 300 | ## 使用内建流 API 301 | 302 | ### 静态 web 服务器 303 | 304 | 想要通过网络高效且支持大文件的发送一个文件到一个客户端。 305 | 306 | #### 不使用流 307 | 308 | ```js 309 | const http = require('http'); 310 | const fs = require('fs'); 311 | 312 | http.createServer((req, res) => { 313 | fs.readFile(`${__dirname}/index.html`, (err, data) => { 314 | if (err) { 315 | res.statusCode = 500; 316 | res.end(String(err)); 317 | return; 318 | } 319 | 320 | res.end(data); 321 | }); 322 | }).listen(8000); 323 | ``` 324 | 325 | #### 使用流 326 | 327 | ```js 328 | const http = require('http'); 329 | const fs = require('fs'); 330 | 331 | http.createServer((req, res) => { 332 | fs.createReadStream(`${__dirname}/index.html`).pipe(res); 333 | }).listen(8000); 334 | ``` 335 | 336 | - 更少代码,更加高效 337 | - 提供一个缓冲区发送到客户端 338 | 339 | #### 使用流 + gzip 340 | 341 | ```js 342 | const http = require('http'); 343 | const fs = require('fs'); 344 | const zlib = require('zlib'); 345 | 346 | http.createServer((req, res) => { 347 | res.writeHead(200, { 348 | 'content-encoding': 'gzip', 349 | }); 350 | fs.createReadStream(`${__dirname}/index.html`) 351 | .pipe(zlib.createGzip()) 352 | .pipe(res); 353 | }).listen(8000); 354 | ``` 355 | 356 | ### 流的错误处理 357 | 358 | ```js 359 | const fs = require('fs'); 360 | const stream = fs.createReadStream('not-found'); 361 | 362 | stream.on('error', (err) => { 363 | console.trace(); 364 | console.error('Stack:', err.stack); 365 | console.error('The error raised was:', err); 366 | }); 367 | ``` 368 | 369 | ## 使用流基类 370 | 371 | ### 可读流 - JSON 行解析器 372 | 373 | 可读流被用来为 I/O 源提供灵活的 API,也可以被用作解析器: 374 | 375 | - 继承自 steam.Readable 类 376 | - 并实现一个 `_read(size)` 方法 377 | 378 | json-lines.txt 379 | 380 | ``` 381 | { "position": 0, "letter": "a" } 382 | { "position": 1, "letter": "b" } 383 | { "position": 2, "letter": "c" } 384 | { "position": 3, "letter": "d" } 385 | { "position": 4, "letter": "e" } 386 | { "position": 5, "letter": "f" } 387 | { "position": 6, "letter": "g" } 388 | { "position": 7, "letter": "h" } 389 | { "position": 8, "letter": "i" } 390 | { "position": 9, "letter": "j" } 391 | ``` 392 | 393 | JSONLineReader.js 394 | 395 | ```js 396 | const stream = require('stream'); 397 | const fs = require('fs'); 398 | const util = require('util'); 399 | 400 | class JSONLineReader extends stream.Readable { 401 | constructor(source) { 402 | super(); 403 | this._source = source; 404 | this._foundLineEnd = false; 405 | this._buffer = ''; 406 | 407 | source.on('readable', () => { 408 | this.read(); 409 | }); 410 | } 411 | 412 | // 所有定制 stream.Readable 类都需要实现 _read 方法 413 | _read(size) { 414 | let chunk; 415 | let line; 416 | let result; 417 | 418 | if (this._buffer.length === 0) { 419 | chunk = this._source.read(); 420 | this._buffer += chunk; 421 | } 422 | 423 | const lineIndex = this._buffer.indexOf('\n'); 424 | 425 | if (lineIndex !== -1) { 426 | line = this._buffer.slice(0, lineIndex); // 从 buffer 的开始截取第一行来获取一些文本进行解析 427 | if (line) { 428 | result = JSON.parse(line); 429 | this._buffer = this._buffer.slice(lineIndex + 1); 430 | this.emit('object', result); // 当一个 JSON 记录解析出来的时候,触发一个 object 事件 431 | this.push(util.inspect(result)); // 将解析好的 SJON 发回内部队列 432 | } else { 433 | this._buffer = this._buffer.slice(1); 434 | } 435 | } 436 | } 437 | } 438 | 439 | const input = fs.createReadStream(`${__dirname}/json-lines.txt`, { 440 | encoding: 'utf8', 441 | }); 442 | const jsonLineReader = new JSONLineReader(input); // 创建一个 JSONLineReader 实例,传递一个文件流给它处理 443 | 444 | jsonLineReader.on('object', (obj) => { 445 | console.log('pos:', obj.position, '- letter:', obj.letter); 446 | }); 447 | ``` 448 | 449 | ### 可写流 - 文字变色 450 | 451 | 可写的流可用于输出数据到底层 I/O: 452 | 453 | - 继承自 `stream.Writable` 454 | - 实现一个 `_write` 方法向底层源数据发送数据 455 | 456 | ```sh 457 | cat json-lines.txt | node stram_writable.js 458 | ``` 459 | 460 | stram_writable.js 461 | 462 | ```js 463 | const stream = require('stream'); 464 | 465 | class GreenStream extends stream.Writable { 466 | constructor(options) { 467 | super(options); 468 | } 469 | 470 | _write(chunk, encoding, cb) { 471 | process.stdout.write(`\u001b[32m${chunk}\u001b[39m`); 472 | cb(); 473 | } 474 | } 475 | 476 | process.stdin.pipe(new GreenStream()); 477 | ``` 478 | 479 | ### 双工流 - 接受和转换数据 480 | 481 | 双工流允许发送和接受数据: 482 | 483 | - 继承自 `stream.Duplex` 484 | - 实现 `_read` 和 `_write` 方法 485 | 486 | ### 转换流 - 解析数据 487 | 488 | 使用流改变数据为另一种格式,并且高效地管理内存: 489 | 490 | - 继承自 `stream.Transform` 491 | - 实现 `_transform` 方法 492 | 493 | ## 测试流 494 | 495 | 使用 Node 内置的断言模块测试 496 | 497 | ```js 498 | const assert = require('assert'); 499 | const fs = require('fs'); 500 | const CSVParser = require('./csvparser'); 501 | 502 | const parser = new CSVParser(); 503 | const actual = []; 504 | 505 | fs.createReadStream(`${__dirname}/sample.csv`) 506 | .pipe(parser); 507 | 508 | process.on('exit', function () { 509 | actual.push(parser.read()); 510 | actual.push(parser.read()); 511 | actual.push(parser.read()); 512 | 513 | const expected = [ 514 | { name: 'Alex', location: 'UK', role: 'admin' }, 515 | { name: 'Sam', location: 'France', role: 'user' }, 516 | { name: 'John', location: 'Canada', role: 'user' }, 517 | ]; 518 | 519 | assert.deepEqual(expected, actual); 520 | }); 521 | ``` 522 | 523 | # 文件系统 524 | 525 | ## fs 模块交互 526 | 527 | - POSIX 文件 I/O 528 | - 文件流 529 | - 批量文件 I/O 530 | - 文件监控 531 | 532 | ## POSIX 文件系统 533 | 534 | | fs 方法 | 描述 | 535 | | :----------- | :--------------------------------------------------------- | 536 | | fs.truncate | 截断或者拓展文件到制定的长度 | 537 | | fs.ftruncate | 和 truncate 一样,但将文件描述符作为参数 | 538 | | fs.chown | 改变文件的所有者以及组 | 539 | | fs.fchown | 和 chown 一样,但将文件描述符作为参数 | 540 | | fs.lchown | 和 chown 一样,但不解析符号链接 | 541 | | fs.stat | 获取文件状态 | 542 | | fs.lstat | 和 stat 一样,但是返回信息是关于符号链接而不是它指向的内容 | 543 | | fs.fstat | 和 stat 一样,但将文件描述符作为参数 | 544 | | fs.link | 创建一个硬链接 | 545 | | fs.symlink | 创建一个软连接 | 546 | | fs.readlink | 读取一个软连接的值 | 547 | | fs.realpath | 返回规范的绝对路径名 | 548 | | fs.unlink | 删除文件 | 549 | | fs.rmdir | 删除文件目录 | 550 | | fs.mkdir | 创建文件目录 | 551 | | fs.readdir | 读取一个文件目录的内容 | 552 | | fs.close | 关闭一个文件描述符 | 553 | | fs.open | 打开或者创建一个文件用来读取或者写入 | 554 | | fs.utimes | 设置文件的读取和修改时间 | 555 | | fs.futimes | 和 utimes 一样,但将文件描述符作为参数 | 556 | | fs.fsync | 同步磁盘中的文件数据 | 557 | | fs.write | 写入数据到一个文件 | 558 | | fs.read | 读取一个文件的数据 | 559 | 560 | ```js 561 | const fs = require('fs'); 562 | const assert = require('assert'); 563 | 564 | const fd = fs.openSync('./file.txt', 'w+'); 565 | const writeBuf = new Buffer('some data to write'); 566 | fs.writeSync(fd, writeBuf, 0, writeBuf.length, 0); 567 | 568 | const readBuf = new Buffer(writeBuf.length); 569 | fs.readSync(fd, readBuf, 0, writeBuf.length, 0); 570 | assert.equal(writeBuf.toString(), readBuf.toString()); 571 | 572 | fs.closeSync(fd); 573 | ``` 574 | 575 | ## 读写流 576 | 577 | ```js 578 | const fs = require('fs'); 579 | const readable = fs.createReadStream('./original.txt'); 580 | const writeable = fs.createWriteStream('./copy.txt'); 581 | readable.pipe(writeable); 582 | ``` 583 | 584 | ## 文件监控 585 | 586 | `fs.watchFile` 比 `fs.watch` 低效,但更好用。 587 | 588 | ## 同步读取与 require 589 | 590 | 同步 fs 的方法应该在第一次初始化应用的时候使用。 591 | 592 | ```js 593 | const fs = require('fs'); 594 | const config = JSON.parse(fs.readFileSync('./config.json').toString()); 595 | init(config); 596 | ``` 597 | 598 | require: 599 | 600 | ```js 601 | const config = require('./config.json); 602 | init(config); 603 | ``` 604 | 605 | - 模块会被全局缓冲,其他文件也加载并修改,会影响到整个系统加载了此文件的模块 606 | - 可以通过 `Object.freeze` 来冻结一个对象 607 | 608 | ## 文件描述 609 | 610 | 文件描述是在操作系统中管理的在进程中打开文件所关联的一些数字或者索引。操作系统通过指派一个唯一的整数给每个打开的文件用来查看关于这个文件 611 | 612 | | Stream | 文件描述 | 描述 | 613 | | ------ | -------- | -------- | 614 | | stdin | 0 | 标准输入 | 615 | | stdout | 1 | 标准输出 | 616 | | stderr | 2 | 标准错误 | 617 | 618 | `console.log('Log')` 是 `process.stdout.write('log')` 的语法糖。 619 | 620 | 一个文件描述是 open 以及 openSync 方法调用返回的一个数字 621 | 622 | ```js 623 | const fd = fs.openSync('myfile', 'a'); 624 | console.log(typeof fd === 'number'); // true 625 | ``` 626 | 627 | ## 文件锁 628 | 629 | 协同多个进程同时访问一个文件,保证文件的完整性以及数据不能丢失: 630 | 631 | - 强制锁(在内核级别执行) 632 | - 咨询锁(非强制,只在涉及到进程订阅了相同的锁机制) 633 | - `node-fs-ext` 通过 `flock` 锁住一个文件 634 | - 使用锁文件 635 | - 进程 A 尝试创建一个锁文件,并且成功了 636 | - 进程 A 已经获得了这个锁,可以修改共享的资源 637 | - 进程 B 尝试创建一个锁文件,但失败了,无法修改共享的资源 638 | 639 | Node 实现锁文件 640 | 641 | - 使用独占标记创建锁文件 642 | - 使用 mkdir 创建锁文件 643 | 644 | ### 独占标记 645 | 646 | ```js 647 | // 所有需要打开文件的方法,fs.writeFile、fs.createWriteStream、fs.open 都有一个 x 标记 648 | // 这个文件应该已独占打开,若这个文件存在,文件不能被打开 649 | fs.open('config.lock', 'wx', (err) => { 650 | if (err) { return console.err(err); } 651 | }); 652 | 653 | // 最好将当前进程号写进文件锁中 654 | // 当有异常的时候就知道最后这个锁的进程 655 | fs.writeFile( 656 | 'config.lock', 657 | process.pid, 658 | { flogs: 'wx' }, 659 | (err) => { 660 | if (err) { return console.error(err) }; 661 | }, 662 | ); 663 | ``` 664 | 665 | ### mkdir 文件锁 666 | 667 | 独占标记有个问题,可能有些系统不能识别 `0_EXCL` 标记。另一个方案是把锁文件换成一个目录,PID 可以写入目录中的一个文件。 668 | 669 | ```js 670 | fs.mkidr('config.lock', (err) => { 671 | if (err) { return console.error(err); } 672 | fs.writeFile(`/config.lock/${process.pid}`, (err) => { 673 | if (err) { return console.error(err); } 674 | }); 675 | }); 676 | ``` 677 | 678 | ### lock 模块实现 679 | 680 | https://github.com/npm/lockfile 681 | 682 | ```js 683 | const fs = require('fs'); 684 | const lockDir = 'config.lock'; 685 | let hasLock = false; 686 | 687 | exports.lock = function (cb) { // 获取锁 688 | if (hasLock) { return cb(); } // 已经获取了一个锁 689 | fs.mkdir(lockDir, function (err) { 690 | if (err) { return cb(err); } // 无法创建锁 691 | 692 | fs.writeFile(lockDir + '/' + process.pid, function (err) { // 把 PID写入到目录中以便调试 693 | if (err) { console.error(err); } // 无法写入 PID,继续运行 694 | hasLock = true; // 锁创建了 695 | return cb(); 696 | }); 697 | }); 698 | }; 699 | 700 | exports.unlock = function (cb) { // 解锁方法 701 | if (!hasLock) { return cb(); } // 如果没有需要解开的锁 702 | fs.unlink(lockDir + '/' + process.pid, function (err) { 703 | if (err) { return cb(err); } 704 | 705 | fs.rmdir(lockDir, function (err) { 706 | if (err) return cb(err); 707 | hasLock = false; 708 | cb(); 709 | }); 710 | }); 711 | }; 712 | 713 | process.on('exit', function () { 714 | if (hasLock) { 715 | fs.unlinkSync(lockDir + '/' + process.pid); // 如果还有锁,在退出之前同步删除掉 716 | fs.rmdirSync(lockDir); 717 | console.log('removed lock'); 718 | } 719 | }); 720 | ``` 721 | 722 | ## 递归文件操作 723 | 724 | 一个线上库:[mkdirp](https://github.com/substack/node-mkdirp) 725 | 726 | 递归:要解决我们的问题就要先解决更小的相同的问题。 727 | 728 | ``` 729 | dir-a 730 | ├── dir-b 731 | │ ├── dir-c 732 | │ │ ├── dir-d 733 | │ │ │ └── file-e.png 734 | │ │ └── file-e.png 735 | │ ├── file-c.js 736 | │ └── file-d.txt 737 | ├── file-a.js 738 | └── file-b.txt 739 | ``` 740 | 741 | 查找模块:`find /asset/dir-a -name="file.*"` 742 | 743 | ```js 744 | [ 745 | 'dir-a/dir-b/dir-c/dir-d/file-e.png', 746 | 'dir-a/dir-b/dir-c/file-e.png', 747 | 'dir-a/dir-b/file-c.js', 748 | 'dir-a/dir-b/file-d.txt', 749 | 'dir-a/file-a.js', 750 | 'dir-a/file-b.txt', 751 | ] 752 | ``` 753 | 754 | ```js 755 | const fs = require('fs'); 756 | const join = require('path').join; 757 | 758 | // 同步查找 759 | exports.findSync = function (nameRe, startPath) { 760 | const results = []; 761 | 762 | function finder(path) { 763 | const files = fs.readdirSync(path); 764 | 765 | for (let i = 0; i < files.length; i++) { 766 | const fpath = join(path, files[i]); 767 | const stats = fs.statSync(fpath); 768 | 769 | if (stats.isDirectory()) { finder(fpath); } 770 | 771 | if (stats.isFile() && nameRe.test(files[i])) { 772 | results.push(fpath); 773 | } 774 | } 775 | } 776 | 777 | finder(startPath); 778 | return results; 779 | }; 780 | 781 | // 异步查找 782 | exports.find = function (nameRe, startPath, cb) { // cb 可以传入 console.log,灵活 783 | const results = []; 784 | let asyncOps = 0; // 2 785 | 786 | function finder(path) { 787 | asyncOps++; 788 | fs.readdir(path, function (er, files) { 789 | if (er) { return cb(er); } 790 | 791 | files.forEach(function (file) { 792 | const fpath = join(path, file); 793 | 794 | asyncOps++; 795 | fs.stat(fpath, function (er, stats) { 796 | if (er) { return cb(er); } 797 | 798 | if (stats.isDirectory()) finder(fpath); 799 | 800 | if (stats.isFile() && nameRe.test(file)) { 801 | results.push(fpath); 802 | } 803 | 804 | asyncOps--; 805 | if (asyncOps == 0) { 806 | cb(null, results); 807 | } 808 | }); 809 | }); 810 | 811 | asyncOps--; 812 | if (asyncOps == 0) { 813 | cb(null, results); 814 | } 815 | }); 816 | } 817 | 818 | finder(startPath); 819 | }; 820 | 821 | console.log(exports.findSync(/file.*/, `${__dirname}/dir-a`)); 822 | console.log(exports.find(/file.*/, `${__dirname}/dir-a`, console.log)); 823 | ``` 824 | 825 | ## 监视文件和文件夹 826 | 827 | 想要监听一个文件或者目录,并在文件更改后执行一个动作。 828 | 829 | ```js 830 | const fs = require('fs'); 831 | fs.watch('./watchdir', console.log); // 稳定且快 832 | fs.watchFile('./watchdir', console.log); // 跨平台 833 | ``` 834 | 835 | ## 逐行地读取文件流 836 | 837 | ```js 838 | const fs = require('fs'); 839 | const readline = require('readline'); 840 | 841 | const rl = readline.createInterface({ 842 | input: fs.createReadStream('/etc/hosts'), 843 | crlfDelay: Infinity 844 | }); 845 | 846 | rl.on('line', (line) => { 847 | console.log(`cc ${line}`); 848 | const extract = line.match(/(\d+\.\d+\.\d+\.\d+) (.*)/); 849 | }); 850 | ``` 851 | 852 | # 网络 853 | 854 | ## 获取本地 IP 855 | 856 | ```js 857 | function get_local_ip() { 858 | const interfaces = require('os').networkInterfaces(); 859 | let IPAdress = ''; 860 | for (const devName in interfaces) { 861 | const iface = interfaces[devName]; 862 | for (let i = 0; i < iface.length; i++) { 863 | const alias = iface[i]; 864 | if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { 865 | IPAdress = alias.address; 866 | } 867 | } 868 | } 869 | return IPAdress; 870 | } 871 | ``` 872 | 873 | ## TCP 客户端 874 | 875 | NodeJS 使用 `net` 模块创建 TCP 连接和服务。 876 | 877 | ### 启动与测试 TCP 878 | 879 | ```js 880 | const assert = require('assert'); 881 | const net = require('net'); 882 | let clients = 0; 883 | let expectedAssertions = 2; 884 | 885 | const server = net.createServer(function (client) { 886 | clients++; 887 | const clientId = clients; 888 | console.log('Client connected:', clientId); 889 | 890 | client.on('end', function () { 891 | console.log('Client disconnected:', clientId); 892 | }); 893 | 894 | client.write('Welcome client: ' + clientId); 895 | client.pipe(client); 896 | }); 897 | 898 | server.listen(8000, function () { 899 | console.log('Server started on port 8000'); 900 | 901 | runTest(1, function () { 902 | runTest(2, function () { 903 | console.log('Tests finished'); 904 | assert.equal(0, expectedAssertions); 905 | server.close(); 906 | }); 907 | }); 908 | }); 909 | 910 | function runTest(expectedId, done) { 911 | const client = net.connect(8000); 912 | 913 | client.on('data', function (data) { 914 | const expected = 'Welcome client: ' + expectedId; 915 | assert.equal(data.toString(), expected); 916 | expectedAssertions--; 917 | client.end(); 918 | }); 919 | 920 | client.on('end', done); 921 | } 922 | ``` 923 | 924 | ## UDP 客户端 925 | 926 | 利用 `dgram` 模块创建数据报 `socket`,然后利用 `socket.send` 发送数据。 927 | 928 | ### 文件发送服务 929 | 930 | ```js 931 | const dgram = require('dgram'); 932 | const fs = require('fs'); 933 | const port = 41230; 934 | const defaultSize = 16; 935 | 936 | function Client(remoteIP) { 937 | const inStream = fs.createReadStream(__filename); // 从当前文件创建可读流 938 | const socket = dgram.createSocket('udp4'); // 创建新的数据流 socket 作为客户端 939 | 940 | inStream.on('readable', function () { 941 | sendData(); // 当可读流准备好,开始发送数据到服务器 942 | }); 943 | 944 | function sendData() { 945 | const message = inStream.read(defaultSize); // 读取数据块 946 | 947 | if (!message) { 948 | return socket.unref(); // 客户端完成任务后,使用 unref 安全关闭它 949 | } 950 | 951 | // 发送数据到服务器 952 | socket.send(message, 0, message.length, port, remoteIP, function () { 953 | sendData(); 954 | } 955 | ); 956 | } 957 | } 958 | 959 | function Server() { 960 | const socket = dgram.createSocket('udp4'); // 创建一个 socket 提供服务 961 | 962 | socket.on('message', function (msg) { 963 | process.stdout.write(msg.toString()); 964 | }); 965 | 966 | socket.on('listening', function () { 967 | console.log('Server ready:', socket.address()); 968 | }); 969 | 970 | socket.bind(port); 971 | } 972 | 973 | if (process.argv[2] === 'client') { // 根据命令行选项确定运行客户端还是服务端 974 | new Client(process.argv[3]); 975 | } else { 976 | new Server(); 977 | } 978 | ``` 979 | 980 | ## HTTP 客户端 981 | 982 | 使用 `http.createServer` 和 `http.createClient` 运行 HTTP 服务。 983 | 984 | ### 启动与测试 HTTP 985 | 986 | ```js 987 | const assert = require('assert'); 988 | const http = require('http'); 989 | 990 | const server = http.createServer(function(req, res) { 991 | res.writeHead(200, { 'Content-Type': 'text/plain' }); // 写入基于文本的响应头 992 | res.write('Hello, world.'); // 发送消息回客户端 993 | res.end(); 994 | }); 995 | 996 | server.listen(8000, function() { 997 | console.log('Listening on port 8000'); 998 | }); 999 | 1000 | const req = http.request({ port: 8000}, function(res) { // 创建请求 1001 | console.log('HTTP headers:', res.headers); 1002 | res.on('data', function(data) { // 给 data 事件创建监听,确保和期望值一致 1003 | console.log('Body:', data.toString()); 1004 | assert.equal('Hello, world.', data.toString()); 1005 | assert.equal(200, res.statusCode); 1006 | server.unref(); 1007 | console.log('测试完成'); 1008 | }); 1009 | }); 1010 | 1011 | req.end(); 1012 | ``` 1013 | 1014 | ### 重定向 1015 | 1016 | HTTP 标准定义了标识重定向发生时的状态码,它也指出了客户端应该检查无限循环。 1017 | 1018 | - 300:多重选择 1019 | - 301:永久移动到新位置 1020 | - 302:找到重定向跳转 1021 | - 303:参见其他信息 1022 | - 304:没有改动 1023 | - 305:使用代理 1024 | - 307:临时重定向 1025 | 1026 | ```js 1027 | const http = require('http'); 1028 | const https = require('https'); 1029 | const url = require('url'); // 有很多接续 URLs 的方法 1030 | 1031 | // 构造函数被用来创建一个对象来构成请求对象的声明周期 1032 | function Request() { 1033 | this.maxRedirects = 10; 1034 | this.redirects = 0; 1035 | } 1036 | 1037 | Request.prototype.get = function(href, callback) { 1038 | const uri = url.parse(href); // 解析 URLs 成为 Node http 模块使用的格式,确定是否使用 HTTPS 1039 | const options = { host: uri.host, path: uri.path }; 1040 | const httpGet = uri.protocol === 'http:' ? http.get : https.get; 1041 | 1042 | console.log('GET:', href); 1043 | 1044 | function processResponse(response) { 1045 | if (response.statusCode >= 300 && response.statusCode < 400) { // 检查状态码是否在 HTTP 重定向范围 1046 | if (this.redirects >= this.maxRedirects) { 1047 | this.error = new Error('Too many redirects for: ' + href); 1048 | } else { 1049 | this.redirects++; // 重定向计数自增 1050 | href = url.resolve(options.host, response.headers.location); // 使用 url.resolve 确保相对路径的 URLs 转换为绝对路径 URLs 1051 | return this.get(href, callback); 1052 | } 1053 | } 1054 | 1055 | response.url = href; 1056 | response.redirects = this.redirects; 1057 | 1058 | console.log('Redirected:', href); 1059 | 1060 | function end() { 1061 | console.log('Connection ended'); 1062 | callback(this.error, response); 1063 | } 1064 | 1065 | response.on('data', function(data) { 1066 | console.log('Got data, length:', data.length); 1067 | }); 1068 | 1069 | response.on('end', end.bind(this)); // 绑定回调到 Request 实例,确保能拿到实例属性 1070 | } 1071 | 1072 | httpGet(options, processResponse.bind(this)) 1073 | .on('error', function(err) { 1074 | callback(err); 1075 | }); 1076 | }; 1077 | 1078 | const request = new Request(); 1079 | request.get('http://google.com/', function(err, res) { 1080 | if (err) { 1081 | console.error(err); 1082 | } else { 1083 | console.log(` 1084 | Fetched URL: ${res.url} with ${res.redirects} redirects 1085 | `); 1086 | process.exit(); 1087 | } 1088 | }); 1089 | ``` 1090 | 1091 | ### HTTP 代理 1092 | 1093 | - ISP 使用透明代理使网络更加高效 1094 | - 使用缓存代理服务器减少宽带 1095 | - Web 应用程序的 DevOps 利用他们提升应用程序性能 1096 | 1097 | ```js 1098 | const http = require('http'); 1099 | const url = require('url'); 1100 | 1101 | http.createServer(function(req, res) { 1102 | console.log('start request:', req.url); 1103 | const options = url.parse(req.url); 1104 | console.log(options); 1105 | options.headers = req.headers; 1106 | const proxyRequest = http.request(options, function(proxyResponse) { // 创建请求来复制原始的请求 1107 | proxyResponse.on('data', function(chunk) { // 监听数据,返回给浏览器 1108 | console.log('proxyResponse length:', chunk.length); 1109 | res.write(chunk, 'binary'); 1110 | }); 1111 | 1112 | proxyResponse.on('end', function() { // 追踪代理请求完成 1113 | console.log('proxied request ended'); 1114 | res.end(); 1115 | }); 1116 | 1117 | res.writeHead(proxyResponse.statusCode, proxyResponse.headers); // 发送头部信息给服务器 1118 | }); 1119 | 1120 | req.on('data', function(chunk) { // 捕获从浏览器发送到服务器的数据 1121 | console.log('in request length:', chunk.length); 1122 | proxyRequest.write(chunk, 'binary'); 1123 | }); 1124 | 1125 | req.on('end', function() { // 追踪原始的请求什么时候结束 1126 | console.log('original request ended'); 1127 | proxyRequest.end(); 1128 | }); 1129 | }).listen(8888); // 监听来自本地浏览器的连接 1130 | ``` 1131 | 1132 | ### 封装 request-promise 1133 | 1134 | ```js 1135 | const https = require('https'); 1136 | const promisify = require('util').promisify; 1137 | 1138 | https.get[promisify.custom] = function getAsync(options) { 1139 | return new Promise((resolve, reject) => { 1140 | https.get(options, (response) => { 1141 | response.end = new Promise((resolve) => response.on('end', resolve)); 1142 | resolve(response); 1143 | }).on('error', reject); 1144 | }); 1145 | }; 1146 | const rp = promisify(https.get); 1147 | 1148 | (async () => { 1149 | const res = await rp('https://jsonmock.hackerrank.com/api/movies/search/?Title=Spiderman&page=1'); 1150 | let body = ''; 1151 | res.on('data', (chunk) => body += chunk); 1152 | await res.end; 1153 | 1154 | console.log(body); 1155 | })(); 1156 | ``` 1157 | 1158 | ## DNS 请求 1159 | 1160 | 使用 `dns` 模块创建 DNS 请求。 1161 | 1162 | - A:`dns.resolve`,A 记录存储 IP 地址 1163 | - TXT:`dns.resulveTxt`,文本值可以用于在 DNS 上构建其他服务 1164 | - SRV:`dns.resolveSrv`,服务记录定义服务的定位数据,通常包含主机名和端口号 1165 | - NS:`dns.resolveNs`,指定域名服务器 1166 | - CNAME:`dns.resolveCname`,相关的域名记录,设置为域名而不是 IP 地址 1167 | 1168 | ```js 1169 | const dns = require('dns'); 1170 | 1171 | dns.resolve('www.chenng.cn', function (err, addresses) { 1172 | if (err) { 1173 | console.error(err); 1174 | } 1175 | 1176 | console.log('Addresses:', addresses); 1177 | }); 1178 | ``` 1179 | 1180 | ## crypto 库加密解密 1181 | 1182 | ```js 1183 | const crypto = require('crypto') 1184 | 1185 | function aesEncrypt(data, key = 'key') { 1186 | const cipher = crypto.createCipher('aes192', key) 1187 | let crypted = cipher.update(data, 'utf8', 'hex') 1188 | crypted += cipher.final('hex') 1189 | return crypted 1190 | } 1191 | 1192 | function aesDecrypt(encrypted, key = 'key') { 1193 | const decipher = crypto.createDecipher('aes192', key) 1194 | let decrypted = decipher.update(encrypted, 'hex', 'utf8') 1195 | decrypted += decipher.final('utf8') 1196 | return decrypted 1197 | } 1198 | ``` 1199 | 1200 | ## 发起 HTTP 请求的方法 1201 | 1202 | - HTTP 标准库 1203 | - 无需安装外部依赖 1204 | - 需要以块为单位接受数据,自己监听 end 事件 1205 | - HTTP 和 HTTPS 是两个模块,需要区分使用 1206 | - Request 库 1207 | - 使用方便 1208 | - 有 promise 版本 `request-promise` 1209 | - Axios 1210 | - 既可以用在浏览器又可以用在 NodeJS 1211 | - 可以使用 axios.all 并发多个请求 1212 | - SuperAgent 1213 | - 可以链式使用 1214 | - node-fetch 1215 | - 浏览器的 fetch 移植过来的 1216 | 1217 | # 子进程 1218 | 1219 | ## 执行外部应用 1220 | 1221 | ### 基本概念 1222 | 1223 | - 4个异步方法:exec、execFile、fork、spawn 1224 | - Node 1225 | - fork:想将一个 Node 进程作为一个独立的进程来运行的时候使用,是的计算处理和文件描述器脱离 Node 主进程 1226 | - 非 Node 1227 | - spawn:处理一些会有很多子进程 I/O 时、进程会有大量输出时使用 1228 | - execFile:只需执行一个外部程序的时候使用,执行速度快,处理用户输入相对安全 1229 | - exec:想直接访问线程的 shell 命令时使用,一定要注意用户输入 1230 | - 3个同步方法:execSync、execFileSync、spawnSync 1231 | - 通过 API 创建出来的子进程和父进程没有任何必然联系 1232 | 1233 | ### execFile 1234 | 1235 | - 会把输出结果缓存好,通过回调返回最后结果或者异常信息 1236 | 1237 | ```js 1238 | const cp = require('child_process'); 1239 | 1240 | cp.execFile('echo', ['hello', 'world'], (err, stdout, stderr) => { 1241 | if (err) { console.error(err); } 1242 | console.log('stdout: ', stdout); 1243 | console.log('stderr: ', stderr); 1244 | }); 1245 | ``` 1246 | 1247 | ### spawn 1248 | 1249 | - 通过流可以使用有大量数据输出的外部应用,节约内存 1250 | - 使用流提高数据响应效率 1251 | - spawn 方法返回一个 I/O 的流接口 1252 | 1253 | #### 单一任务 1254 | 1255 | ```js 1256 | const cp = require('child_process'); 1257 | 1258 | const child = cp.spawn('echo', ['hello', 'world']); 1259 | child.on('error', console.error); 1260 | child.stdout.pipe(process.stdout); 1261 | child.stderr.pipe(process.stderr); 1262 | ``` 1263 | 1264 | #### 多任务串联 1265 | 1266 | ```js 1267 | const cp = require('child_process'); 1268 | const path = require('path'); 1269 | 1270 | const cat = cp.spawn('cat', [path.resolve(__dirname, 'messy.txt')]); 1271 | const sort = cp.spawn('sort'); 1272 | const uniq = cp.spawn('uniq'); 1273 | 1274 | cat.stdout.pipe(sort.stdin); 1275 | sort.stdout.pipe(uniq.stdin); 1276 | uniq.stdout.pipe(process.stdout); 1277 | ``` 1278 | 1279 | ### exec 1280 | 1281 | - 只有一个字符串命令 1282 | - 和 shell 一模一样 1283 | 1284 | ```js 1285 | const cp = require('child_process'); 1286 | 1287 | cp.exec(`cat ${__dirname}/messy.txt | sort | uniq`, (err, stdout, stderr) => { 1288 | console.log(stdout); 1289 | }); 1290 | ``` 1291 | 1292 | ### fork 1293 | 1294 | - fork 方法会开发一个 IPC 通道,不同的 Node 进程进行消息传送 1295 | - 一个子进程消耗 30ms 启动时间和 10MB 内存 1296 | - 子进程:`process.on('message')`、`process.send()` 1297 | - 父进程:`child.on('message')`、`child.send()` 1298 | 1299 | #### 父子通信 1300 | 1301 | ```js 1302 | // parent.js 1303 | const cp = require('child_process'); 1304 | 1305 | const child = cp.fork('./child', { silent: true }); 1306 | child.send('monkeys'); 1307 | child.on('message', function (message) { 1308 | console.log('got message from child', message, typeof message); 1309 | }) 1310 | child.stdout.pipe(process.stdout); 1311 | 1312 | setTimeout(function () { 1313 | child.disconnect(); 1314 | }, 3000); 1315 | ``` 1316 | 1317 | ```js 1318 | // child.js 1319 | process.on('message', function (message) { 1320 | console.log('got one', message); 1321 | process.send('no pizza'); 1322 | process.send(1); 1323 | process.send({ my: 'object' }); 1324 | process.send(false); 1325 | process.send(null); 1326 | }); 1327 | 1328 | console.log(process); 1329 | ``` 1330 | 1331 | ## 常用技巧 1332 | 1333 | ### 退出时杀死所有子进程 1334 | 1335 | - 保留对由 spawn 返回的 ChildProcess 对象的引用,并在退出主进程时将其杀死 1336 | 1337 | ```js 1338 | const spawn = require('child_process').spawn; 1339 | const children = []; 1340 | 1341 | process.on('exit', function () { 1342 | console.log('killing', children.length, 'child processes'); 1343 | children.forEach(function (child) { 1344 | child.kill(); 1345 | }); 1346 | }); 1347 | 1348 | children.push(spawn('/bin/sleep', ['10'])); 1349 | children.push(spawn('/bin/sleep', ['10'])); 1350 | children.push(spawn('/bin/sleep', ['10'])); 1351 | 1352 | setTimeout(function () { process.exit(0); }, 3000); 1353 | ``` 1354 | 1355 | ## Cluster 的理解 1356 | 1357 | - 解决 NodeJS 单进程无法充分利用多核 CPU 问题 1358 | - 通过 master-cluster 模式可以使得应用更加健壮 1359 | - Cluster 底层是 child_process 模块,除了可以发送普通消息,还可以发送底层对象 `TCP`、`UDP` 等 1360 | - TCP 主进程发送到子进程,子进程能根据消息重建出 TCP 连接,Cluster 可以决定 fork 出合适的硬件资源的子进程数 1361 | 1362 | # Node 多线程 1363 | 1364 | ## 单线程问题 1365 | 1366 | - 对 cpu 利用不足 1367 | - 某个未捕获的异常可能会导致整个程序的退出 1368 | 1369 | ## Node 线程 1370 | 1371 | - Node 进程占用了 7 个线程 1372 | - Node 中最核心的是 v8 引擎,在 Node 启动后,会创建 v8 的实例,这个实例是多线程的 1373 | - 主线程:编译、执行代码 1374 | - 编译/优化线程:在主线程执行的时候,可以优化代码 1375 | - 分析器线程:记录分析代码运行时间,为 Crankshaft 优化代码执行提供依据 1376 | - 垃圾回收的几个线程 1377 | - JavaScript 的执行是单线程的,但 Javascript 的宿主环境,无论是 Node 还是浏览器都是多线程的 1378 | 1379 | ## 异步 IO 1380 | 1381 | - Node 中有一些 IO 操作(DNS,FS)和一些 CPU 密集计算(Zlib,Crypto)会启用 Node 的线程池 1382 | - 线程池默认大小为 4,可以手动更改线程池默认大小 1383 | 1384 | ```js 1385 | process.env.UV_THREADPOOL_SIZE = 64 1386 | ``` 1387 | 1388 | ## cluster 多进程 1389 | 1390 | ```js 1391 | const cluster = require('cluster'); 1392 | const http = require('http'); 1393 | const numCPUs = require('os').cpus().length; 1394 | 1395 | if (cluster.isMaster) { 1396 | console.log(`主进程 ${process.pid} 正在运行`); 1397 | for (let i = 0; i < numCPUs; i++) { 1398 | cluster.fork(); 1399 | } 1400 | 1401 | cluster.on('exit', (worker, code, signal) => { 1402 | console.log(`工作进程 ${worker.process.pid} 已退出`); 1403 | }); 1404 | } else { 1405 | // 工作进程可以共享任何 TCP 连接。 1406 | // 在本例子中,共享的是 HTTP 服务器。 1407 | http.createServer((req, res) => { 1408 | res.writeHead(200); 1409 | res.end('Hello World'); 1410 | }).listen(8000); 1411 | console.log(`工作进程 ${process.pid} 已启动`); 1412 | } 1413 | ``` 1414 | 1415 | - 一共有 9 个进程,其中一个主进程,cpu 个数 x cpu 核数 = 2 x 4 = 8 个 子进程 1416 | - 无论 child_process 还是 cluster,都不是多线程模型,而是多进程模型 1417 | - 应对单线程问题,通常使用多进程的方式来模拟多线程 1418 | 1419 | ## 真 Node 多线程 1420 | 1421 | - Node 10.5.0 的发布,给出了一个实验性质的模块 worker_threads 给 Node 提供真正的多线程能力 1422 | - worker_thread 模块中有 4 个对象和 2 个类 1423 | - isMainThread: 是否是主线程,源码中是通过 threadId === 0 进行判断的。 1424 | - MessagePort: 用于线程之间的通信,继承自 EventEmitter。 1425 | - MessageChannel: 用于创建异步、双向通信的通道实例。 1426 | - threadId: 线程 ID。 1427 | - Worker: 用于在主线程中创建子线程。第一个参数为 filename,表示子线程执行的入口。 1428 | - parentPort: 在 worker 线程里是表示父进程的 MessagePort 类型的对象,在主线程里为 null 1429 | - workerData: 用于在主进程中向子进程传递数据(data 副本) 1430 | 1431 | ```js 1432 | const { 1433 | isMainThread, 1434 | parentPort, 1435 | workerData, 1436 | threadId, 1437 | MessageChannel, 1438 | MessagePort, 1439 | Worker 1440 | } = require('worker_threads'); 1441 | 1442 | function mainThread() { 1443 | for (let i = 0; i < 5; i++) { 1444 | const worker = new Worker(__filename, { workerData: i }); 1445 | worker.on('exit', code => { console.log(`main: worker stopped with exit code ${code}`); }); 1446 | worker.on('message', msg => { 1447 | console.log(`main: receive ${msg}`); 1448 | worker.postMessage(msg + 1); 1449 | }); 1450 | } 1451 | } 1452 | 1453 | function workerThread() { 1454 | console.log(`worker: workerDate ${workerData}`); 1455 | parentPort.on('message', msg => { 1456 | console.log(`worker: receive ${msg}`); 1457 | }), 1458 | parentPort.postMessage(workerData); 1459 | } 1460 | 1461 | if (isMainThread) { 1462 | mainThread(); 1463 | } else { 1464 | workerThread(); 1465 | } 1466 | ``` 1467 | 1468 | ### 线程通信 1469 | 1470 | ```js 1471 | const assert = require('assert'); 1472 | const { 1473 | Worker, 1474 | MessageChannel, 1475 | MessagePort, 1476 | isMainThread, 1477 | parentPort 1478 | } = require('worker_threads'); 1479 | if (isMainThread) { 1480 | const worker = new Worker(__filename); 1481 | const subChannel = new MessageChannel(); 1482 | worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); 1483 | subChannel.port2.on('message', (value) => { 1484 | console.log('received:', value); 1485 | }); 1486 | } else { 1487 | parentPort.once('message', (value) => { 1488 | assert(value.hereIsYourPort instanceof MessagePort); 1489 | value.hereIsYourPort.postMessage('the worker is sending this'); 1490 | value.hereIsYourPort.close(); 1491 | }); 1492 | } 1493 | ``` 1494 | 1495 | ## 多进程 vs 多线程 1496 | 1497 | 进程是资源分配的最小单位,线程是CPU调度的最小单位 1498 | 1499 | # 分布式 1500 | 1501 | ## 分布式锁 1502 | 1503 | - 在单机场景下,可以使用语言的内置锁来实现进程同步 1504 | - 在分布式场景下,需要同步的进程可能位于不同的节点上,那么就需要使用分布式锁 1505 | 1506 | ### 数据库的唯一索引 1507 | 1508 | 获得锁时向表中插入一条记录,释放锁时删除这条记录。 1509 | 1510 | - 锁没有失效时间,解锁失败的话其它进程无法再获得该锁。 1511 | - 只能是非阻塞锁,插入失败直接就报错了,无法重试。 1512 | - 不可重入,已经获得锁的进程也必须重新获取锁。 1513 | 1514 | ### Redis 的 SETNX 指令 1515 | 1516 | 使用 SETNX(set if not exist)指令插入一个键值对,如果 Key 已经存在,那么会返回 False,否则插入成功并返回 True 1517 | 1518 | - SETNX 指令和数据库的唯一索引类似,保证了只存在一个 Key 的键值对,可以用一个 Key 的键值对是否存在来判断是否存于锁定状态 1519 | - EXPIRE 指令可以为一个键值对设置一个过期时间,从而避免了数据库唯一索引实现方式中释放锁失败的问题 1520 | 1521 | ### Redis 的 RedLock 算法 1522 | 1523 | 使用了多个 Redis 实例来实现分布式锁,这是为了保证在发生单点故障时仍然可用 1524 | 1525 | - 尝试从 N 个相互独立 Redis 实例获取锁 1526 | - 计算获取锁消耗的时间,只有当这个时间小于锁的过期时间,并且从大多数(N / 2 + 1)实例上获取了锁,那么就认为锁获取成功了 1527 | - 如果锁获取失败,就到每个实例上释放锁 1528 | 1529 | # 项目管理 1530 | 1531 | ## 组件式构建 1532 | 1533 | https://github.com/i0natan/nodebestpractices/blob/master/sections/projectstructre/breakintcomponents.chinese.md 1534 | 1535 | ## 多环境配置 1536 | 1537 | - JSON 配置文件 1538 | - 环境变量 1539 | 使用第三方模块管理(nconf) 1540 | 1541 | ## 依赖管理 1542 | 1543 | - dependencies:模块正常运行需要的依赖 1544 | - devDependencies:开发时候需要的依赖 1545 | - optionalDependencies:非必要依赖,某种程度上增强 1546 | - peerDependencies:运行时依赖,限定版本 1547 | 1548 | # 异常处理 1549 | 1550 | ## 处理未捕获的异常 1551 | 1552 | - 除非开发者记得添加.catch语句,在这些地方抛出的错误都不会被 uncaughtException 事件处理程序来处理,然后消失掉。 1553 | - Node 应用不会奔溃,但可能导致内存泄露 1554 | 1555 | ```js 1556 | process.on('uncaughtException', (error) => { 1557 | // 我刚收到一个从未被处理的错误 1558 | // 现在处理它,并决定是否需要重启应用 1559 | errorManagement.handler.handleError(error); 1560 | if (!errorManagement.handler.isTrustedError(error)) { 1561 | process.exit(1); 1562 | } 1563 | }); 1564 | 1565 | process.on('unhandledRejection', (reason, p) => { 1566 | // 我刚刚捕获了一个未处理的promise rejection, 1567 | // 因为我们已经有了对于未处理错误的后备的处理机制(见下面) 1568 | // 直接抛出,让它来处理 1569 | throw reason; 1570 | }); 1571 | ``` 1572 | 1573 | ## 通过 domain 管理异常 1574 | 1575 | - 通过 domain 模块的 create 方法创建实例 1576 | - 某个错误已经任何其他错误都会被同一个 error 处理方法处理 1577 | - 任何在这个回调中导致错误的代码都会被 domain 覆盖到 1578 | - 允许我们代码在一个沙盒运行,并且可以使用 res 对象给用户反馈 1579 | 1580 | ```js 1581 | const domain = require('domain'); 1582 | const audioDomain = domain.create(); 1583 | 1584 | audioDomain.on('error', function(err) { 1585 | console.log('audioDomain error:', err); 1586 | }); 1587 | 1588 | audioDomain.run(function() { 1589 | const musicPlayer = new MusicPlayer(); 1590 | musicPlayer.play(); 1591 | }); 1592 | ``` 1593 | 1594 | ## Joi 验证参数 1595 | 1596 | ```js 1597 | const memberSchema = Joi.object().keys({ 1598 | password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/), 1599 | birthyear: Joi.number().integer().min(1900).max(2013), 1600 | email: Joi.string().email(), 1601 | }); 1602 | 1603 | function addNewMember(newMember) { 1604 | //assertions come first 1605 | Joi.assert(newMember, memberSchema); //throws if validation fails 1606 | 1607 | //other logic here 1608 | } 1609 | ``` 1610 | 1611 | ## Kibana 系统监控 1612 | 1613 | https://github.com/i0natan/nodebestpractices/blob/master/sections/production/smartlogging.chinese.md 1614 | 1615 | # 上线实践 1616 | 1617 | ## 使用 winston 记录日记 1618 | 1619 | ```js 1620 | var winston = require('winston'); 1621 | var moment = require('moment'); 1622 | 1623 | const logger = new (winston.Logger)({ 1624 | transports: [ 1625 | new (winston.transports.Console)({ 1626 | timestamp: function() { 1627 | return moment().format('YYYY-MM-DD HH:mm:ss') 1628 | }, 1629 | formatter: function(params) { 1630 | let time = params.timestamp() // 时间 1631 | let message = params.message // 手动信息 1632 | let meta = params.meta && Object.keys(params.meta).length ? '\n\t'+ JSON.stringify(params.meta) : '' 1633 | return `${time} ${message}` 1634 | }, 1635 | }), 1636 | new (winston.transports.File)({ 1637 | filename: `${__dirname}/../winston/winston.log`, 1638 | json: false, 1639 | timestamp: function() { 1640 | return moment().format('YYYY-MM-DD HH:mm:ss') 1641 | }, 1642 | formatter: function(params) { 1643 | let time = params.timestamp() // 时间 1644 | let message = params.message // 手动信息 1645 | let meta = params.meta && Object.keys(params.meta).length ? '\n\t'+ JSON.stringify(params.meta) : '' 1646 | return `${time} ${message}` 1647 | } 1648 | }) 1649 | ] 1650 | }) 1651 | 1652 | module.exports = logger 1653 | 1654 | // logger.error('error') 1655 | // logger.warm('warm') 1656 | // logger.info('info') 1657 | ``` 1658 | 1659 | ## 委托反向代理 1660 | 1661 | Node 处理 CPU 密集型任务,如 gzipping,SSL termination 等,表现糟糕。相反,使用一个真正的中间件服务像 Nginx 更好。否则可怜的单线程 Node 将不幸地忙于处理网络任务,而不是处理应用程序核心,性能会相应降低。 1662 | 1663 | 虽然 express.js 通过一些 connect 中间件处理静态文件,但你不应该使用它。Nginx 可以更好地处理静态文件,并可以防止请求动态内容堵塞我们的 node 进程。 1664 | 1665 | ```sh 1666 | # 配置 gzip 压缩 1667 | gzip on; 1668 | gzip_comp_level 6; 1669 | gzip_vary on; 1670 | 1671 | # 配置 upstream 1672 | upstream myApplication { 1673 | server 127.0.0.1:3000; 1674 | server 127.0.0.1:3001; 1675 | keepalive 64; 1676 | } 1677 | 1678 | #定义 web server 1679 | server { 1680 | # configure server with ssl and error pages 1681 | listen 80; 1682 | listen 443 ssl; 1683 | ssl_certificate /some/location/sillyfacesociety.com.bundle.crt; 1684 | error_page 502 /errors/502.html; 1685 | 1686 | # handling static content 1687 | location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) { 1688 | root /usr/local/silly_face_society/node/public; 1689 | access_log off; 1690 | expires max; 1691 | } 1692 | ``` 1693 | 1694 | ## 检测有漏洞的依赖项 1695 | 1696 | https://docs.npmjs.com/cli/audit 1697 | 1698 | ## PM2 HTTP 集群配置 1699 | 1700 | ### 工作线程配置 1701 | 1702 | - `pm2 start app.js -i 4`,`-i 4` 是以 cluster_mode 形式运行 app,有 4 个工作线程,如果配置 `0`,PM2 会根据 CPU 核心数来生成对应的工作线程 1703 | - 工作线程挂了 PM2 会立即将其重启 1704 | - `pm2 scale ` 对集群进行扩展 1705 | 1706 | ### PM2 自动启动 1707 | 1708 | - `pm2 save` 保存当前运行的应用 1709 | - `pm2 startup` 启动 1710 | 1711 | # 性能实践 1712 | 1713 | ## 避免使用 Lodash 1714 | 1715 | - 使用像 lodash 这样的方法库这会导致不必要的依赖和较慢的性能 1716 | - 随着新的 V8 引擎和新的 ES 标准的引入,原生方法得到了改进,现在性能比方法库提高了 50% 1717 | 1718 | 使用 ESLint 插件检测: 1719 | 1720 | ```js 1721 | { 1722 | "extends": [ 1723 | "plugin:you-dont-need-lodash-underscore/compatible" 1724 | ] 1725 | } 1726 | ``` 1727 | 1728 | ## benchmark 1729 | 1730 | ```js 1731 | const _ = require('lodash'), 1732 | __ = require('underscore'), 1733 | Suite = require('benchmark').Suite, 1734 | opts = require('./utils'); 1735 | //cf. https://github.com/Berkmann18/NativeVsUtils/blob/master/utils.js 1736 | 1737 | const concatSuite = new Suite('concat', opts); 1738 | const array = [0, 1, 2]; 1739 | 1740 | concatSuite.add('lodash', () => _.concat(array, 3, 4, 5)) 1741 | .add('underscore', () => __.concat(array, 3, 4, 5)) 1742 | .add('native', () => array.concat(3, 4, 5)) 1743 | .run({ 'async': true }); 1744 | ``` 1745 | 1746 | ## 使用 prof 进行性能分析 1747 | 1748 | - 使用 tick-processor 工具处理分析 1749 | 1750 | ```sh 1751 | node --prof profile-test.js 1752 | ``` 1753 | 1754 | ```sh 1755 | npm install tick -g 1756 | 1757 | node-tick-processor 1758 | ``` 1759 | 1760 | ## 使用 headdump 堆快照 1761 | 1762 | - 代码加载模块进行快照文件生成 1763 | - Chrome Profiles 加载快照文件 1764 | 1765 | ```sh 1766 | yarn add heapdump -D 1767 | ``` 1768 | 1769 | ```js 1770 | const heapdump = require('heapdump'); 1771 | const string = '1 string to rule them all'; 1772 | 1773 | const leakyArr = []; 1774 | let count = 2; 1775 | setInterval(function () { 1776 | leakyArr.push(string.replace(/1/g, count++)); 1777 | }, 0); 1778 | 1779 | setInterval(function () { 1780 | if (heapdump.writeSnapshot()) console.log('wrote snapshot'); 1781 | }, 20000); 1782 | ``` 1783 | 1784 | # 应用安全清单 1785 | 1786 | ## helmet 设置安全响应头 1787 | 1788 | 检测头部配置:[Security Headers](https://securityheaders.com/)。 1789 | 1790 | 应用程序应该使用安全的 header 来防止攻击者使用常见的攻击方式,诸如跨站点脚本攻击(XSS)、跨站请求伪造(CSRF)。可以使用模块 [helmet](https://www.npmjs.com/package/helmet) 轻松进行配置。 1791 | 1792 | - 构造 1793 | - X-Frame-Options:sameorigin。提供点击劫持保护,iframe 只能同源。 1794 | - 传输 1795 | - Strict-Transport-Security:max-age=31536000; includeSubDomains。强制 HTTPS,这减少了web 应用程序中错误通过 cookies 和外部链接,泄露会话数据,并防止中间人攻击 1796 | - 内容 1797 | - X-Content-Type-Options:nosniff。阻止从声明的内容类型中嗅探响应,减少了用户上传恶意内容造成的风险 1798 | - Content-Type:text/html;charset=utf-8。指示浏览器将页面解释为特定的内容类型,而不是依赖浏览器进行假设 1799 | - XSS 1800 | - X-XSS-Protection:1; mode=block。启用了内置于最新 web 浏览器中的跨站点脚本(XSS)过滤器 1801 | - 下载 1802 | - X-Download-Options:noopen。 1803 | - 缓存 1804 | - Cache-Control:no-cache。web 应中返回的数据可以由用户浏览器以及中间代理缓存。该指令指示他们不要保留页面内容,以免其他人从这些缓存中访问敏感内容 1805 | - Pragma:no-cache。同上 1806 | - Expires:-1。web 响应中返回的数据可以由用户浏览器以及中间代理缓存。该指令通过将到期时间设置为一个值来防止这种情况。 1807 | - 访问控制 1808 | - Access-Control-Allow-Origin:not *。'Access-Control-Allow-Origin: *' 默认在现代浏览器中禁用 1809 | - X-Permitted-Cross-Domain-Policies:master-only。指示只有指定的文件在此域中才被视为有效 1810 | - 内容安全策略 1811 | - Content-Security-Policy:内容安全策略需要仔细调整并精确定义策略 1812 | - 服务器信息 1813 | - Server:不显示。 1814 | 1815 | ## 使用 security-linter 插件 1816 | 1817 | 使用安全检验插件 [eslint-plugin-security](https://github.com/nodesecurity/eslint-plugin-security) 或者 [tslint-config-security](https://www.npmjs.com/package/tslint-config-security)。 1818 | 1819 | ## koa-ratelimit 限制并发请求 1820 | 1821 | DOS 攻击非常流行而且相对容易处理。使用外部服务,比如 cloud 负载均衡, cloud 防火墙, nginx, 或者(对于小的,不是那么重要的app)一个速率限制中间件(比如 [koa-ratelimit](https://github.com/koajs/ratelimit)),来实现速率限制。 1822 | 1823 | ## 纯文本机密信息放置 1824 | 1825 | 存储在源代码管理中的机密信息必须进行加密和管理 (滚动密钥(rolling keys)、过期时间、审核等)。使用 pre-commit/push 钩子防止意外提交机密信息。 1826 | 1827 | ## ORM/ODM 库防止查询注入漏洞 1828 | 1829 | 要防止 SQL/NoSQL 注入和其他恶意攻击, 请始终使用 ORM/ODM 或 database 库来转义数据或支持命名的或索引的参数化查询, 并注意验证用户输入的预期类型。不要只使用 JavaScript 模板字符串或字符串串联将值插入到查询语句中, 因为这会将应用程序置于广泛的漏洞中。 1830 | 1831 | 库: 1832 | 1833 | - TypeORM 1834 | - sequelize 1835 | - mongoose 1836 | - Knex 1837 | - Objection.js 1838 | - waterline 1839 | 1840 | ## 使用 Bcrypt 代替 Crypto 1841 | 1842 | 密码或机密信息(API 密钥)应该使用安全的 hash + salt 函数([bcrypt](https://www.npmjs.com/package/bcrypt))来存储, 因为性能和安全原因, 这应该是其 JavaScript 实现的首选。 1843 | 1844 | ```js 1845 | // 使用10个哈希回合异步生成安全密码 1846 | bcrypt.hash('myPassword', 10, function(err, hash) { 1847 | // 在用户记录中存储安全哈希 1848 | }); 1849 | 1850 | // 将提供的密码输入与已保存的哈希进行比较 1851 | bcrypt.compare('somePassword', hash, function(err, match) { 1852 | if(match) { 1853 | // 密码匹配 1854 | } else { 1855 | // 密码不匹配 1856 | } 1857 | }); 1858 | ``` 1859 | 1860 | ## 转义 HTML、JS 和 CSS 输出 1861 | 1862 | 发送给浏览器的不受信任数据可能会被执行, 而不是显示, 这通常被称为跨站点脚本(XSS)攻击。使用专用库将数据显式标记为不应执行的纯文本内容(例如:编码、转义),可以减轻这种问题。 1863 | 1864 | ## 验证传入的 JSON schemas 1865 | 1866 | 验证传入请求的 body payload,并确保其符合预期要求, 如果没有, 则快速报错。为了避免每个路由中繁琐的验证编码, 您可以使用基于 JSON 的轻量级验证架构,比如 [jsonschema](https://www.npmjs.com/package/jsonschema) 或 [joi](https://www.npmjs.com/package/joi) 1867 | 1868 | ## 支持黑名单的 JWT 1869 | 1870 | 当使用 JSON Web Tokens(例如, 通过 [Passport.js](https://github.com/jaredhanson/passport)), 默认情况下, 没有任何机制可以从发出的令牌中撤消访问权限。一旦发现了一些恶意用户活动, 只要它们持有有效的标记, 就无法阻止他们访问系统。通过实现一个不受信任令牌的黑名单,并在每个请求上验证,来减轻此问题。 1871 | 1872 | ```js 1873 | const jwt = require('express-jwt'); 1874 | const blacklist = require('express-jwt-blacklist'); 1875 | 1876 | app.use(jwt({ 1877 | secret: 'my-secret', 1878 | isRevoked: blacklist.isRevoked 1879 | })); 1880 | 1881 | app.get('/logout', function (req, res) { 1882 | blacklist.revoke(req.user) 1883 | res.sendStatus(200); 1884 | }); 1885 | ``` 1886 | 1887 | ## 限制每个用户允许的登录请求 1888 | 1889 | 一类保护暴力破解的中间件,比如 express-brute,应该被用在 express 的应用中,来防止暴力/字典攻击;这类攻击主要应用于一些敏感路由,比如 `/admin` 或者 `/login`,基于某些请求属性, 如用户名, 或其他标识符, 如正文参数等。否则攻击者可以发出无限制的密码匹配尝试, 以获取对应用程序中特权帐户的访问权限。 1890 | 1891 | ```js 1892 | const ExpressBrute = require('express-brute'); 1893 | const RedisStore = require('express-brute-redis'); 1894 | 1895 | const redisStore = new RedisStore({ 1896 | host: '127.0.0.1', 1897 | port: 6379 1898 | }); 1899 | 1900 | // Start slowing requests after 5 failed 1901 | // attempts to login for the same user 1902 | const loginBruteforce = new ExpressBrute(redisStore, { 1903 | freeRetries: 5, 1904 | minWait: 5 * 60 * 1000, // 5 minutes 1905 | maxWait: 60 * 60 * 1000, // 1 hour 1906 | failCallback: failCallback, 1907 | handleStoreError: handleStoreErrorCallback 1908 | }); 1909 | 1910 | app.post('/login', 1911 | loginBruteforce.getMiddleware({ 1912 | key: function (req, res, next) { 1913 | // prevent too many attempts for the same username 1914 | next(req.body.username); 1915 | } 1916 | }), // error 403 if we hit this route too often 1917 | function (req, res, next) { 1918 | if (User.isValidLogin(req.body.username, req.body.password)) { 1919 | // reset the failure counter for valid login 1920 | req.brute.reset(function () { 1921 | res.redirect('/'); // logged in 1922 | }); 1923 | } else { 1924 | // handle invalid user 1925 | } 1926 | } 1927 | ); 1928 | ``` 1929 | 1930 | ## 使用非 root 用户运行 Node.js 1931 | 1932 | Node.js 作为一个具有无限权限的 root 用户运行,这是一种普遍的情景。例如,在 Docker 容器中,这是默认行为。建议创建一个非 root 用户,并保存到 Docker 镜像中(下面给出了示例),或者通过调用带有"-u username" 的容器来代表此用户运行该进程。否则在服务器上运行脚本的攻击者在本地计算机上获得无限制的权利 (例如,改变 iptable,引流到他的服务器上) 1933 | 1934 | ```dockerfile 1935 | FROM node:latest 1936 | COPY package.json . 1937 | RUN npm install 1938 | COPY . . 1939 | EXPOSE 3000 1940 | USER node 1941 | CMD ["node", "server.js"] 1942 | ``` 1943 | 1944 | ## 使用反向代理或中间件限制负载大小 1945 | 1946 | 请求 body 有效载荷越大, Node.js 的单线程就越难处理它。这是攻击者在没有大量请求(DOS/DDOS 攻击)的情况下,就可以让服务器跪下的机会。在边缘上(例如,防火墙,ELB)限制传入请求的 body 大小,或者通过配置 `express body parser` 仅接收小的载荷,可以减轻这种问题。否则您的应用程序将不得不处理大的请求, 无法处理它必须完成的其他重要工作, 从而导致对 DOS 攻击的性能影响和脆弱性。 1947 | 1948 | express: 1949 | 1950 | ```js 1951 | const express = require('express'); 1952 | 1953 | const app = express(); 1954 | 1955 | // body-parser defaults to a body size limit of 300kb 1956 | app.use(express.json({ limit: '300kb' })); 1957 | 1958 | // Request with json body 1959 | app.post('/json', (req, res) => { 1960 | 1961 | // Check if request payload content-type matches json 1962 | // because body-parser does not check for content types 1963 | if (!req.is('json')) { 1964 | return res.sendStatus(415); // Unsupported media type if request doesn't have JSON body 1965 | } 1966 | 1967 | res.send('Hooray, it worked!'); 1968 | }); 1969 | 1970 | app.listen(3000, () => console.log('Example app listening on port 3000!')); 1971 | ``` 1972 | 1973 | nginx: 1974 | 1975 | ``` 1976 | http { 1977 | ... 1978 | # Limit the body size for ALL incoming requests to 1 MB 1979 | client_max_body_size 1m; 1980 | } 1981 | 1982 | server { 1983 | ... 1984 | # Limit the body size for incoming requests to this specific server block to 1 MB 1985 | client_max_body_size 1m; 1986 | } 1987 | 1988 | location /upload { 1989 | ... 1990 | # Limit the body size for incoming requests to this route to 1 MB 1991 | client_max_body_size 1m; 1992 | } 1993 | ``` 1994 | 1995 | ## 防止 RegEx 让 NodeJS 过载 1996 | 1997 | 匹配文本的用户输入需要大量的 CPU 周期来处理。在某种程度上,正则处理是效率低下的,比如验证 10 个单词的单个请求可能阻止整个 event loop 长达6秒。由于这个原因,偏向第三方的验证包,比如[validator.js](https://github.com/chriso/validator.js),而不是采用正则,或者使用 [safe-regex](https://github.com/substack/safe-regex) 来检测有问题的正则表达式。 1998 | 1999 | ```js 2000 | const saferegex = require('safe-regex'); 2001 | const emailRegex = /^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$/; 2002 | 2003 | // should output false because the emailRegex is vulnerable to redos attacks 2004 | console.log(saferegex(emailRegex)); 2005 | 2006 | // instead of the regex pattern, use validator: 2007 | const validator = require('validator'); 2008 | console.log(validator.isEmail('liran.tal@gmail.com')); 2009 | ``` 2010 | 2011 | ## 在沙箱中运行不安全代码 2012 | 2013 | 当任务执行在运行时给出的外部代码时(例如, 插件), 使用任何类型的沙盒执行环境保护主代码,并隔离开主代码和插件。这可以通过一个专用的过程来实现 (例如:cluster.fork()), 无服务器环境或充当沙盒的专用 npm 包。 2014 | 2015 | - 一个专门的子进程 - 这提供了一个快速的信息隔离, 但要求制约子进程, 限制其执行时间, 并从错误中恢复 2016 | - 一个基于云的无服务框架满足所有沙盒要求,但动态部署和调用Faas方法不是本部分的内容 2017 | - 一些 npm 库,比如 [sandbox](https://www.npmjs.com/package/sandbox) 和 [vm2](https://www.npmjs.com/package/vm2) 允许通过一行代码执行隔离代码。尽管后一种选择在简单中获胜, 但它提供了有限的保护。 2018 | 2019 | ```js 2020 | const Sandbox = require("sandbox"); 2021 | const s = new Sandbox(); 2022 | 2023 | s.run( "lol)hai", function( output ) { 2024 | console.log(output); 2025 | //output='Synatx error' 2026 | }); 2027 | 2028 | // Example 4 - Restricted code 2029 | s.run( "process.platform", function( output ) { 2030 | console.log(output); 2031 | //output=Null 2032 | }) 2033 | 2034 | // Example 5 - Infinite loop 2035 | s.run( "while (true) {}", function( output ) { 2036 | console.log(output); 2037 | //output='Timeout' 2038 | }) 2039 | ``` 2040 | 2041 | ## 隐藏客户端的错误详细信息 2042 | 2043 | 默认情况下, 集成的 express 错误处理程序隐藏错误详细信息。但是, 极有可能, 您实现自己的错误处理逻辑与自定义错误对象(被许多人认为是最佳做法)。如果这样做, 请确保不将整个 Error 对象返回到客户端, 这可能包含一些敏感的应用程序详细信息。否则敏感应用程序详细信息(如服务器文件路径、使用中的第三方模块和可能被攻击者利用的应用程序的其他内部工作流)可能会从 stack trace 发现的信息中泄露。 2044 | 2045 | ``` 2046 | // production error handler 2047 | // no stacktraces leaked to user 2048 | app.use(function(err, req, res, next) { 2049 | res.status(err.status || 500); 2050 | res.render('error', { 2051 | message: err.message, 2052 | error: {} 2053 | }); 2054 | }); 2055 | ``` 2056 | 2057 | ## 对 npm 或 Yarn,配置 2FA 2058 | 2059 | 开发链中的任何步骤都应使用 MFA(多重身份验证)进行保护, npm/Yarn 对于那些能够掌握某些开发人员密码的攻击者来说是一个很好的机会。使用开发人员凭据, 攻击者可以向跨项目和服务广泛安装的库中注入恶意代码。甚至可能在网络上公开发布。在 npm 中启用两层身份验证(2-factor-authentication), 攻击者几乎没有机会改变您的软件包代码。 2060 | 2061 | https://itnext.io/eslint-backdoor-what-it-is-and-how-to-fix-the-issue-221f58f1a8c8 2062 | 2063 | ## session 中间件设置 2064 | 2065 | 每个 web 框架和技术都有其已知的弱点,告诉攻击者我们使用的 web 框架对他们来说是很大的帮助。使用 session 中间件的默认设置, 可以以类似于 `X-Powered-Byheader` 的方式向模块和框架特定的劫持攻击公开您的应用。尝试隐藏识别和揭露技术栈的任何内容(例如:Nonde.js, express)。否则可以通过不安全的连接发送cookie, 攻击者可能会使用会话标识来标识web应用程序的基础框架以及特定于模块的漏洞。 2066 | 2067 | ```js 2068 | // using the express session middleware 2069 | app.use(session({ 2070 | secret: 'youruniquesecret', // secret string used in the signing of the session ID that is stored in the cookie 2071 | name: 'youruniquename', // set a unique name to remove the default connect.sid 2072 | cookie: { 2073 | httpOnly: true, // minimize risk of XSS attacks by restricting the client from reading the cookie 2074 | secure: true, // only send cookie over https 2075 | maxAge: 60000*60*24 // set cookie expiry length in ms 2076 | } 2077 | })); 2078 | ``` 2079 | 2080 | ## csurf 防止 CSRF 2081 | 2082 | 路由层: 2083 | 2084 | ```js 2085 | var cookieParser = require('cookie-parser'); 2086 | var csrf = require('csurf'); 2087 | var bodyParser = require('body-parser'); 2088 | var express = require('express'); 2089 | 2090 | // 设置路由中间件 2091 | var csrfProtection = csrf({ cookie: true }); 2092 | var parseForm = bodyParser.urlencoded({ extended: false }); 2093 | 2094 | var app = express(); 2095 | 2096 | // 我们需要这个,因为在 csrfProtection 中 “cookie” 是正确的 2097 | app.use(cookieParser()); 2098 | 2099 | app.get('/form', csrfProtection, function(req, res) { 2100 | // 将 CSRFToken 传递给视图 2101 | res.render('send', { csrfToken: req.csrfToken() }); 2102 | }); 2103 | 2104 | app.post('/process', parseForm, csrfProtection, function(req, res) { 2105 | res.send('data is being processed'); 2106 | }); 2107 | ``` 2108 | 2109 | 展示层: 2110 | 2111 | ```html 2112 |
2113 | 2114 | 2115 | Favorite color: 2116 | 2117 |
2118 | ``` 2119 | 2120 | # 综合应用 2121 | 2122 | ## watch 服务 2123 | 2124 | ```js 2125 | const fs = require('fs'); 2126 | const exec = require('child_process').exec; 2127 | 2128 | function watch() { 2129 | const child = exec('node server.js'); 2130 | const watcher = fs.watch(__dirname + '/server.js', function () { 2131 | console.log('File changed, reloading.'); 2132 | child.kill(); 2133 | watcher.close(); 2134 | watch(); 2135 | }); 2136 | } 2137 | 2138 | watch(); 2139 | ``` 2140 | 2141 | ## RESTful web 应用 2142 | 2143 | - REST 意思是表征性状态传输 2144 | - 使用正确的 HTTP 方法、URLs 和头部信息来创建语义化 RESTful API 2145 | 2146 | - GET /gages:获取 2147 | - POST /pages:创建 2148 | - GET /pages/10:获取 pages10 2149 | - PATCH /pages/10:更新 pages10 2150 | - PUT /pages/10:替换 pages10 2151 | - DELETE /pages/10:删除 pages10 2152 | 2153 | ```js 2154 | let app; 2155 | const express = require('express'); 2156 | const routes = require('./routes'); 2157 | 2158 | module.exports = app = express(); 2159 | 2160 | app.use(express.json()); // 使用 JSON body 解析 2161 | app.use(express.methodOverride()); // 允许一个查询参数来制定额外的 HTTP 方法 2162 | 2163 | // 资源使用的路由 2164 | app.get('/pages', routes.pages.index); 2165 | app.get('/pages/:id', routes.pages.show); 2166 | app.post('/pages', routes.pages.create); 2167 | app.patch('/pages/:id', routes.pages.patch); 2168 | app.put('/pages/:id', routes.pages.update); 2169 | app.del('/pages/:id', routes.pages.remove); 2170 | ``` 2171 | 2172 | ## 中间件应用 2173 | 2174 | ```js 2175 | const express = require('express'); 2176 | const app = express(); 2177 | const Schema = require('validate'); 2178 | const xml2json = require('xml2json'); 2179 | const util = require('util'); 2180 | const Page = new Schema(); 2181 | 2182 | Page.path('title').type('string').required(); // 数据校验确保页面有标题 2183 | 2184 | function ValidatorError(errors) { // 从错误对象继承,校验出现的错误在错误中间件处理 2185 | this.statusCode = 400; 2186 | this.message = errors.join(', '); 2187 | } 2188 | util.inherits(ValidatorError, Error); 2189 | 2190 | function xmlMiddleware(req, res, next) { // 处理 xml 的中间件 2191 | if (!req.is('xml')) return next(); 2192 | 2193 | let body = ''; 2194 | req.on('data', function (str) { // 从客户端读到数据时触发 2195 | body += str; 2196 | }); 2197 | 2198 | req.on('end', function () { 2199 | req.body = xml2json.toJson(body.toString(), { 2200 | object: true, 2201 | sanitize: false, 2202 | }); 2203 | next(); 2204 | }); 2205 | } 2206 | 2207 | function checkValidXml(req, res, next) { // 数据校验中间件 2208 | const page = Page.validate(req.body.page); 2209 | if (page.errors.length) { 2210 | next(new ValidatorError(page.errors)); // 传递错误给 next 阻止路由继续运行 2211 | } else { 2212 | next(); 2213 | } 2214 | } 2215 | 2216 | function errorHandler(err, req, res, next) { // 错误处理中间件 2217 | console.error('errorHandler', err); 2218 | res.send(err.statusCode || 500, err.message); 2219 | } 2220 | 2221 | app.use(xmlMiddleware); // 应用 XML 中间件到所有的请求中 2222 | 2223 | app.post('/pages', checkValidXml, function (req, res) { // 特定的请求校验 xml 2224 | console.log('Valid page:', req.body.page); 2225 | res.send(req.body); 2226 | }); 2227 | 2228 | app.use(errorHandler); // 添加错误处理中间件 2229 | 2230 | app.listen(3000); 2231 | ``` 2232 | 2233 | ## 通过事件组织应用 2234 | 2235 | ```js 2236 | // 监听用户注册成功消息,绑定邮件程序 2237 | const express = require('express'); 2238 | const app = express(); 2239 | const emails = require('./emails'); 2240 | const routes = require('./routes'); 2241 | 2242 | app.use(express.json()); 2243 | 2244 | app.post('/users', routes.users.create); // 设置路由创建用户 2245 | 2246 | app.on('user:created', emails.welcome); // 监听创建成功事件,绑定 email 代码 2247 | 2248 | module.exports = app; 2249 | ``` 2250 | 2251 | ```js 2252 | // 用户注册成功发起事件 2253 | const User = require('./../models/user'); 2254 | 2255 | module.exports.create = function (req, res, next) { 2256 | const user = new User(req.body); 2257 | user.save(function (err) { 2258 | if (err) return next(err); 2259 | res.app.emit('user:created', user); // 当用户成功注册时触发创建用户事件 2260 | res.send('User created'); 2261 | }); 2262 | }; 2263 | ``` 2264 | 2265 | ## WebSocket 与 session 2266 | 2267 | ```js 2268 | const express = require('express'); 2269 | const WebSocketServer = require('ws').Server; 2270 | const parseCookie = express.cookieParser('some secret'); // 加载解析 cookie 中间件,设置密码 2271 | const MemoryStore = express.session.MemoryStore; // 加载要使用的会话存储 2272 | const store = new MemoryStore(); 2273 | 2274 | const app = express(); 2275 | const server = app.listen(process.env.PORT || 3000); 2276 | 2277 | app.use(parseCookie); 2278 | app.use(express.session({ store: store, secret: 'some secret' })); // 告知 Express 使用会话存储和设置密码(使用 session 中间件) 2279 | app.use(express.static(__dirname + '/public')); 2280 | 2281 | app.get('/random', function (req, res) { // 测试测试用的会话值 2282 | req.session.random = Math.random().toString(); 2283 | res.send(200); 2284 | }); 2285 | 2286 | // 设置 WebSocket 服务器,将其传递给 Express 服务器 2287 | // 需要传递已有的 Express 服务(listen 的返回对象) 2288 | const webSocketServer = new WebSocketServer({ server: server }); 2289 | 2290 | // 在连接事件给客户端创建 WebSocket 2291 | webSocketServer.on('connection', function (ws) { 2292 | let session; 2293 | 2294 | ws.on('message', function (data, flags) { 2295 | const message = JSON.parse(data); 2296 | 2297 | // 客户端发送的 JSON,需要一些代码来解析 JSON 字符串确定是否可用 2298 | if (message.type === 'getSession') { 2299 | parseCookie(ws.upgradeReq, null, function (err) { 2300 | // 从 HTTP 的更新请求中获取 WebSocket 的会话 ID 2301 | // 一旦 WebSockets 服务器有一个连接,session ID 可以用=从初始化请求中的 cookies 中获取 2302 | const sid = ws.upgradeReq.signedCookies['connect.sid']; 2303 | 2304 | // 从存储中获取用户的会话信息 2305 | // 只需要在初始化的请求中传递一个引用给解析 cookie 的中间件 2306 | // 然后 session 可以使用 session 存储的 get 方法加载 2307 | store.get(sid, function (err, loadedSession) { 2308 | if (err) console.error(err); 2309 | session = loadedSession; 2310 | ws.send('session.random: ' + session.random, { 2311 | mask: false, 2312 | }); // session 加载后会把一个包含了 session 值的消息发回给客户端 2313 | }); 2314 | }); 2315 | } else { 2316 | ws.send('Unknown command'); 2317 | } 2318 | }); 2319 | }); 2320 | ``` 2321 | 2322 | ```html 2323 | 2324 | 2325 | 2326 | 2327 | 2339 | 2340 | 2341 | 2342 |

WebSocket sessions

2343 |

2344 | 2345 | 2346 | 2347 | ``` 2348 | 2349 | ## Express4 中间件 2350 | 2351 | | package | 描述 | 2352 | | --------------- | ---------------------------------------------------------------- | 2353 | | body-parser | 解析 URL 编码 和 JSON POST 请求的 body 数据 | 2354 | | compression | 压缩服务器响应 | 2355 | | connect-timeout | 请求允许超时 | 2356 | | cookie-parser | 从 HTTP 头部信息中解析 cookies,结果放在 req.cookies | 2357 | | cookie-session | 使用 cookies 来支持简单会话 | 2358 | | csurf | 在会话中添加 token,防御 CSRF 攻击 | 2359 | | errorhandler | Connect 中使用的默认错误处理 | 2360 | | express-session | 简单的会话处理,使用 stores 扩展来吧会话信息写入到数据库或文件中 | 2361 | | method-override | 映射新的 HTTP 动词到请求变量中的 _method | 2362 | | morgan | 日志格式化 | 2363 | | response-time | 跟踪响应时间 | 2364 | | serve-favicon | 发送网站图标 | 2365 | | serve-index | 目录列表 | 2366 | | whost | 允许路由匹配子域名 | 2367 | 2368 | ## JWT 2369 | 2370 | JSON Web Token(缩写 JWT)是目前最流行的跨域认证解决方案。 2371 | 2372 | ### 跨域认证 2373 | 2374 | #### 一般流程 2375 | 2376 | - 用户向服务器发送用户名和密码 2377 | - 服务器验证通过后,在当前对话(session)里面保存相关数据,比如用户角色、登录时间等等 2378 | - 服务器向用户返回一个 session_id,写入用户的 Cookie 2379 | - 用户随后的每一次请求,都会通过 Cookie,将 session_id 传回服务器 2380 | - 服务器收到 session_id,找到前期保存的数据,由此得知用户的身份 2381 | 2382 | #### session 共享 2383 | 2384 | 在服务器集群,要求 session 数据共享,每台服务器都能够读取 session: 2385 | 2386 | - 一种解决方案是 session 数据持久化,写入数据库或别的持久层。各种服务收到请求后,都向持久层请求数据。这种方案的优点是架构清晰,缺点是工程量比较大。另外,持久层万一挂了,就会单点失败。 2387 | - 另一种方案是服务器索性不保存 session 数据了,所有数据都保存在客户端,每次请求都发回服务器。JWT 就是这种方案的一个代表。 2388 | 2389 | ### JWT 2390 | 2391 | #### 原理 2392 | 2393 | - 服务器认证以后,生成一个 JSON 对象,发回给用户 2394 | - 用户与服务端通信的时候,都要发回这个 JSON 对象,服务器完全只靠这个对象认定用户身份 2395 | - 防止篡改会加上签名 2396 | 2397 | #### 数据结构 2398 | 2399 | Header(头部).Payload(负载).Signature(签名): 2400 | 2401 | - Header:JSON,使用 Base64 URL 转成字符串 2402 | - Payload:JSON,使用 Base64 URL 转成字符串 2403 | - Signature:对前两部分的签名 2404 | 2405 | ##### Header 2406 | 2407 | ```js 2408 | { 2409 | "alg": "HS256", // 签名的算法 2410 | "typ": "JWT" // token 的类型 2411 | } 2412 | ``` 2413 | 2414 | ##### Payload 2415 | 2416 | ```js 2417 | { 2418 | // 7 个官方字段 2419 | "iss": "签发人", 2420 | "exp": "过期时间", 2421 | "sub": "主题", 2422 | "aud": "受众", 2423 | "nbf": "生效时间", 2424 | "iat": "签发时间", 2425 | "jti": "编号", 2426 | // 定义私有字段 2427 | "name": "Chenng" 2428 | } 2429 | ``` 2430 | 2431 | ##### Signature 2432 | 2433 | ```sh 2434 | HMACSHA256( 2435 | base64UrlEncode(header) + "." + 2436 | base64UrlEncode(payload), 2437 | secret) # secret 秘钥只有服务器知道 2438 | ``` 2439 | 2440 | 2441 | #### 使用方式 2442 | 2443 | - 客户端收到服务器返回的 JWT,可以储存在 Cookie 里面,也可以储存在 localStorage 2444 | - 放在 Cookie 里面自动发送,但是这样不能跨域,所以更好的做法是放在 HTTP 请求的头信息 Authorization 字段里面 2445 | 2446 | #### 特点 2447 | 2448 | - JWT 不仅可以用于认证,也可以用于交换信息。有效使用 JWT,可以降低服务器查询数据库的次数 2449 | - JWT 的最大缺点是,由于服务器不保存 session 状态,因此无法在使用过程中废止某个 token,或者更改 token 的权限。也就是说,一旦 JWT 签发了,在到期之前就会始终有效,除非服务器部署额外的逻辑 2450 | - JWT 本身包含了认证信息,一旦泄露,任何人都可以获得该令牌的所有权限。为了减少盗用,JWT 的有效期应该设置得比较短。对于一些比较重要的权限,使用时应该再次对用户进行认证 2451 | 2452 | ## koa 2453 | 2454 | ### 核心对象 2455 | 2456 | - HTTP 接收 解析 响应 2457 | - 中间件 执行上下文 2458 | - Koa 中一切的流程都是中间件 2459 | 2460 | ### 源码组成 2461 | 2462 | - application 2463 | - context 2464 | - request 2465 | - response 2466 | 2467 | ### 中间件的使用 2468 | 2469 | ```js 2470 | const Koa = require('koa'); 2471 | 2472 | const app = new Koa(); 2473 | 2474 | const mid1 = async (ctx, next) => { 2475 | ctx.body = 'Hi'; 2476 | await next(); // next 执行下一个中间件 2477 | ctx.body += ' there'; 2478 | }; 2479 | const mid2 = async (ctx, next) => { 2480 | ctx.type = 'text/html; chartset=utf-8'; 2481 | await next(); 2482 | }; 2483 | const mid3 = async (ctx, next) => { 2484 | ctx.body += ' chenng'; 2485 | await next(); 2486 | }; 2487 | 2488 | app.use(mid1); 2489 | app.use(mid2); 2490 | app.use(mid3); 2491 | 2492 | app.listen(2333); 2493 | // Hi chenng there 2494 | ``` 2495 | 2496 | ### 返回媒体资源 2497 | 2498 | ```js 2499 | router 2500 | .get('/api/dynamic_image/codewars', async (ctx, next) => { 2501 | const res = await axios.get('https://www.codewars.com/users/ringcrl'); 2502 | const [, kyu, score] = res.data 2503 | .match(/
Rank:<\/b>(.+?)<\/div>
Honor:<\/b>(.+?)<\/div>/); 2504 | const svg = ` 2505 | 2506 | 2507 | 2508 | ${kyu} 2509 | 2510 | ${score} 2511 | 2512 | `; 2513 | ctx.set('Content-Type', 'image/svg+xml'); 2514 | ctx.body = Buffer.from(svg); 2515 | await next(); 2516 | }); 2517 | ``` 2518 | 2519 | ## Web API 设计 2520 | 2521 | ### 需求 2522 | 2523 | - 易于使用 2524 | - 便于修改 2525 | - 健壮性好 2526 | - 不怕公之于众 2527 | 2528 | ### 重要准则 2529 | 2530 | - 设计容易记忆、功能一目了然 2531 | - 使用合适的 HTTP 方法 2532 | - 选择合适的英语单词,注意单词的单复数形式 2533 | - 使用 OAuth 2.0 进行认证 2534 | 2535 | API 通用资源网站 ProgrammableWeb()中有各种已经公开的 Web API 文档,多观察一下 2536 | 2537 | ## 公钥加密私钥解密 2538 | 2539 | ### 生成公钥私钥 2540 | 2541 | ``` 2542 | 利用 openssl 生成公钥私钥 2543 | 生成公钥:openssl genrsa -out rsa_private_key.pem 1024 2544 | 生成私钥:openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem 2545 | ``` 2546 | 2547 | ### crypto 使用 2548 | 2549 | ```js 2550 | const crypto = require('crypto'); 2551 | const fs = require('fs'); 2552 | 2553 | const publicKey = fs.readFileSync(`${__dirname}/rsa_public_key.pem`).toString('ascii'); 2554 | const privateKey = fs.readFileSync(`${__dirname}/rsa_private_key.pem`).toString('ascii'); 2555 | console.log(publicKey); 2556 | console.log(privateKey); 2557 | const data = 'Chenng'; 2558 | console.log('content: ', data); 2559 | 2560 | //公钥加密 2561 | const encodeData = crypto.publicEncrypt( 2562 | publicKey, 2563 | Buffer.from(data), 2564 | ).toString('base64'); 2565 | console.log('encode: ', encodeData); 2566 | 2567 | //私钥解密 2568 | const decodeData = crypto.privateDecrypt( 2569 | privateKey, 2570 | Buffer.from(encodeData, 'base64'), 2571 | ); 2572 | console.log('decode: ', decodeData.toString()); 2573 | ``` 2574 | 2575 | ## redis 缓存接口 2576 | 2577 | - 部分不用实时更新的数据使用 redis 进行缓存 2578 | - 使用 node-schedule 在每晚定时调用接口 2579 | 2580 | 2581 | ### redis 使用 2582 | 2583 | ```js 2584 | const redis = require('redis'); 2585 | const redisClient = redis.createClient(); 2586 | const getAsync = promisify(redisClient.get).bind(redisClient); 2587 | 2588 | let codewarsRes = JSON.parse(await getAsync('codewarsRes')); 2589 | if (!codewarsRes) { 2590 | const res = await axios.get('https://www.codewars.com/users/ringcrl'); 2591 | codewarsRes = res.data; 2592 | redisClient.set('codewarsRes', JSON.stringify(codewarsRes), 'EX', 86000); 2593 | } 2594 | ``` 2595 | 2596 | ## node-schedule 使用 2597 | 2598 | ```js 2599 | const schedule = require('node-schedule'); 2600 | const axios = require('axios'); 2601 | 2602 | schedule.scheduleJob('* 23 59 * *', function () { 2603 | axios.get('https://static.chenng.cn/api/dynamic_image/leetcode_problems'); 2604 | axios.get('https://static.chenng.cn/api/dynamic_image/leetcode'); 2605 | axios.get('https://static.chenng.cn/api/dynamic_image/codewars'); 2606 | }); 2607 | ``` 2608 | 2609 | ## 跨域共享 Cookie 2610 | 2611 | ### 二级域名共享 Cookie 2612 | 2613 | ```js 2614 | app.use(express.session({ 2615 | secret: conf.secret, 2616 | maxAge: new Date(Date.now() + 3600000), 2617 | cookie: { 2618 | path: '/', 2619 | domain: '.yourdomain.com', 2620 | }, 2621 | store: new MongoStore(conf.sessiondb), 2622 | })); 2623 | ``` 2624 | 2625 | ### 淘宝天猫共享 Cookie 2626 | 2627 | - 淘宝登录后 `.taobao.com` 的接口会带上 Cookie 2628 | - 天猫使用 JSONP 请求一个 `.taobao.com` 的接口,接口返回一段 script,直接把带有 Cookie 的对象设置到 window 下 2629 | 2630 | # 参考地址 2631 | 2632 | - [《Node.js硬实战:115个核心技巧》](https://www.amazon.cn/dp/B01MYX8XG1) 2633 | - [i0natan/nodebestpractices](https://github.com/i0natan/nodebestpractices) 2634 | - [真-Node多线程](https://juejin.im/post/5c63b5676fb9a049ac79a798?utm_source=gold_browser_extension) 2635 | - [CS-Notes](https://github.com/CyC2018/CS-Notes) 2636 | --------------------------------------------------------------------------------