Node Cookbook 3rd-Packt Publishing 2017 读书笔记

这篇博客记录了阅读《Node Cookbook 3rd-Packt Publishing 2017》的笔记,内容涵盖使用DevTools调试Node.js,理解V8调试协议,模块管理,I/O协调,Stream的使用,Web协议,数据库持久化,Web框架,安全处理,性能优化,微服务构建,以及Node.js部署等。重点探讨了如何利用Node.js的调试工具、Stream和Web协议进行高效开发。

Node Cookbook 3rd-Packt Publishing 2017-ReadingNotes.md

调试进程

  • 用DevTools调试Node

      $ mkdir app
      $ cd app
      $ npm init -y
      $ npm install --save express
      $ node --inspect index.js (6.3.0+,这个调试真的不错啊,酷毙了!)

    How it works... 这段内容很有意思,因为它涉及了v8的debugger协议细节

  • 8+ 启动时暂停:node --inspect-brk index.js
  • 命令行调试:node debug index.js
  • Enhancing stack trace output
    • 增加栈深度显示:--stack-trace-limit=21
    • 进一步在代码中指定:Error.stackTraceLimit = Infinity
  • Asynchronous stack traces
    • $ npm install --save-dev longjohn 这是什么原理?
  • 启用debug logs:
    • DEBUG=* node index.js
  • 启用core debug logs:
    • 特殊的环境变量:$ NODE_DEBUG=timer node index.js
    • NODE_DEBUG可设置为下列模块:http net tls stream module timer cluster child_process fs

编写模块

  • npm config set init.author.name "< name here >"
    • npm init(package.json文件里似乎没有依赖字段?)
    • npm version 1.0.0
  • 安装依赖:
    • npm install --save hsl-to-rgb-for-reals
    • --save-dev
  • npm run lint
  • 安装全局依赖不需要sudo(实质是修改了prefix路径):sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
    • 或:npm config set prefix ~/ npm-global(需要添加到PATH中)
  • node -p "require('./')( 0, 100, 100)" (-p选项有点像Perl里的-e)
  • 测试:
    • tap 代码覆盖?
  • 发布模块
    • npm login
    • npm publish --access = public
  • 模块安全
    • npm i -g auditjs
    • prepublish(略)
    • 发布到IPFS:npm install -g stay-cli
  • 使用私有仓库(npm官方也是使用的这个实现吗?还是说仅仅是mock的api?)

Coordinating I/O

  • setInterval(() => process.stdout.write('.'), 10).unref()
  • 监视目录:chokidar

Using Streams

  • stream事件
    • data
    • end(输入流)--> finish(输出流)
    • close,error(不保证一定有触发)
    • pause/resume(都是针对ReadableStream的!pull模型)
  • 使用pipe
    • !产品环境中不要使用,推荐pump(见鬼)
    • backpressure
    • content.pipe( socket, {end: false})
      • content.on('end', ()=>{socket.end()})
    • 验证:同一input可以pipe到多个output???
  • pipe缺少error处理???!不早说,tnnd
    • npm install --save pump
    • pump(input, output, (error)={...})
    • 避免自己手写的boilerplate代码:
      • stream.pipe(res); res.on('close', ()=>{stream.destroy()})
  • pumpify:忽略pipeline中间的transform流,只展示开始的input和最终的output?
  • 创建自己的transform流:through2 ?
    • 推荐使用readable-stream,而不是core stream,以屏蔽不同Node版本的差异?
  • 对象流*
  • from2、to2(见鬼)
  • stream.Readable/Writable
  • flow control:
    • readable流的_read方法依赖于push的驱动,怎么以异步方式连续push多次呢?
    • 包from2 + 嵌套setTimeout???
  • duplex流:const stream = duplexify(ws, rs)
  • Decoupling I/O(???)
  • By default, writable streams have a high watermark of 16,384 bytes (16 KB). 如果超过了仍继续写入就会内存泄露。
    • pipe控制的write每次写不会超过16KB,但直接write可以超过:
      • rs.on(' data', (chunk) = > ws.write( chunk))
      • 这种情况下,需要检查write的返回值,true代表可以继续写,false说明需要暂停,直到drain事件触发:
          rs.resume())
          ws.once('drain', () = > rs.resume())

Wielding Web Protocols

  • 上传文件via PUT和xhr2: 。。。
  • const buffer = Buffer.allocUnsafe(size); ... chunk.copy(buffer, index)

持久化到数据库

  • Postgres jsonb类型?
  • $ npm install --save hiredis(比纯JS的包redis更快?)
  • LevelDB?跟SQLite属于嵌入式环境使用吧

使用Web框架

  • express
  • Hapi
  • Koa(v2: 8+)
    const router = require('koa-router')()
    router.get('/', async function (ctx, next) {
      await next()
      const { title } = ctx.state
      ctx.body = `...`
    }, async (ctx) = > ctx.state = {...});

处理安全

  • express:用helmet增强http响应头部*
  • 防御XSS:url请求参数中用JS嵌入特殊的token(?似乎不是根本的解决方法?)
    • 协议handler类型的XSS(javascript:...)
  • 防御CSRF:cookie sameSite选项?

优化性能

  • HTTP性能基准测试
    • autocannon:POST请求
  • Finding bottlenecks with flamegraphs(用火焰图来寻找瓶颈)
    • 0x ? --pref-basic-prof 使用HTML+D3.js生成图表?
  • 优化同步函数调用
    • node --trace-opt --trace-deopt app.js
  • 优化异步回调
  • Profiling memory

构建微服务系统

  • fuge???
  • 服务发现机制:dns?
    • Consul.io
    • etcd
    • zookeeper
    • P2P协议,如Raft

Deploying Node.js

  • kops: 管理多个k8s集群???
The principles of asynchronous event-driven programming are perfect for today&#39;s web, where efficient, high-concurrency applications are essential for good user experience and a company&#39;s bottom line. The use of Node for tooling and server-side logic with a browser-based, client-side UI leads to a full-stack unilingual experience--everything is JavaScript. This saves developers, architects, project leads, and entire teams the cognitive energy of context-switching between languages, and yields rapid, fluid development cycles. With a thriving community and success stories and investment from major organizations (such as Netflix, IBM, Capital One, Groupon, RedHat, PayPal, Fidelity, and more), Node.js is relevant to enthusiasts, start-ups, and enterprises alike. Since the publication of the first edition of Node Cookbook, the technology, community, thinking, and industry around Node.js has taken significant steps forward. On top of that, the first edition was introductory in nature when it was published; Node.js was new, and there were few developers working with it on a daily basis. These days, developer mindshare around Node.js is widespread, allowing for a higher level of assumed basic understanding. To that end, Node Cookbook, Third Edition is an (almost) complete rewrite of Node Cookbook. It covers far more territory than the first and second edition, with dedicated chapters on debugging, performance, microservices, and deployment (all the topics that are either alluded to or not covered in the former editions). Node Cookbook, Third Edition, not only benefits from the enhanced experience and knowledge acquired by the original author since the first edition was written, but also draws on the expertise of coauthors Mathias Buus, Matteo Collina, and Peter Elger, who provide content for some of the high value chapters in this book.
Over 60 high-quality recipes covering debugging, security, performance, microservices, web frameworks, databases, deployment and more; rewritten for Node.js 8, Node.js 6, and Node.js 4 About This Book Actionable recipes across the full spectrum of Node.js development Cutting edge techniques and tools for measuring and improving performance Best practices for creating readily-scalable production systems Who This Book Is For If you have good knowledge of JavaScript and want to build fast, efficient, scalable client-server solutions, then this book is for you. Some experience with Node.js is assumed to get the most out of this book. If working from a beginner level Node Cookbook 2nd Edition is recommended as a primer for Node Cookbook 3rd Edition. What You Will Learn Debug Node.js programs Write and publish your own Node.js modules Detailed coverage of Node.js core API&#39;s Use web frameworks such as Express, Hapi and Koa for accelerated web application development Apply Node.js streams for low-footprint data processing Fast-track performance knowledge and optimization abilities Persistence strategies, including database integrations with MongoDB, MySQL/MariaDB, Postgres, Redis, and LevelDB Apply critical, essential security concepts Use Node with best-of-breed deployment technologies: Docker, Kubernetes and AWS In Detail Today&#39;s web demands efficient real-time applications and scalability. Asynchronous event-driven programming is ideal for this, and this is where Node.js comes in. Server-side JavaScript has been here since the 90s, but Node got it right. With Node for tooling and server-side logic, and a browser-based client-side UI, everything is JavaScript. This leads to rapid, fluid development cycles. The full-stack, single language experience means less context-switching between languages for developers, architects and whole teams. This book shows you how to build fast, efficient, and scalable client-server solutions using the latest versions of Node. The book begins with debugging tips and tricks of the trade, and how to write your own modules. Then you&#39;ll learn the fundamentals of streams in Node.js, discover I/O control, and how to implement the different web protocols. You&#39;ll find recipes for integrating databases such as MongoDB, MySQL/MariaDB, Postgres, Redis, and LevelDB. We also cover the options for building web application with Express, Hapi and Koa. You will then learn about security essentials in Node.js and advanced optimization tools and techniques. By the end of the book you will have acquired the level of expertise to build production-ready and scalable Node.js systems. The techniques and skills you will learn in this book are based on the best practices developed by nearForm, one of the leaders in Node implementations, who supported the work of the authors on this book. Style and approach This recipe-based practical guide presents each topic with step-by-step instructions on how you can create fast and efficient server side applications using the latest features and capabilities in Node 8 whilst also supporting usage with Node 4 and 6.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值