2016年,Node 决定将 Chrome 浏览器的"开发者工具"做为官方的调试工具,使得 Node 脚本也可使用图形界面调试node
1.准备chrome
建立目录npm
D:\nodejs>mkdir test
D:\nodejs>cd test
生成package.json
文件json
D:\nodejs\test>npm init -y Wrote to D:\nodejs\test\package.json: { "name": "test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
安装 Koa 框架和 koa-route 模块浏览器
D:\nodejs\test>npm install --save koa koa-route npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN test@1.0.0 No description npm WARN test@1.0.0 No repository field. + koa-route@3.2.0 + koa@2.7.0 added 45 packages from 23 contributors and audited 60 packages in 4.74s found 0 vulnerabilities
新建脚本test.js
服务器
const Koa = require('koa'); const router = require('koa-route'); const app = new Koa(); const main = ctx => { ctx.response.body = 'Hello World'; }; const welcome = (ctx, name) => { ctx.response.body = 'Hello ' + name; }; app.use(router.get('/', main)); app.use(router.get('/:name', welcome)); app.listen(3000); console.log('listening on port 3000');
2.调试服务脚本app
运行时,加--inspect
启动调试模式框架
D:\nodejs\test>node --inspect test.js Debugger listening on ws://127.0.0.1:9229/2d21dab8-02a4-4fde-99b3-2bdfecc6bac4 For help, see: https://nodejs.org/en/docs/inspector listening on port 3001
浏览器打开http://127.0.0.1:3001/koa
打开调试工具的方法工具
(1)在 http://127.0.0.1:3001 的窗口打开"开发者工具",左上角有Node 标志
(2)在 Chrome 浏览器的地址栏,键入 chrome://inspect 或 about:inspect
(3)调试工具窗口
Console(控制台)、Source(源码)、Memory(内存)、Profile(性能)
(4)设置断点
浏览器访问http://localhost:3001/baby,页面会显示正在等待服务器返回
切换到调试工具,能够看到 Node 主线程处于暂停(paused)阶段
进入 Console 面板,输入 name
正处在断点处的上下文(context)
Sources 面板,右侧能够看到 Watch、Call Stack、Scope、Breakpoints 等折叠项
Scope 中,能够看到 Local 做用域和 Global 做用域里面的全部变量
在Local 做用域里面修改变量name,并继续运行
页面显示
(5)终止调试
命令下,ctrl+c
3.调试非服务脚本
Web 服务脚本会一直在后台运行,可是非服务脚本,运行完就结束了,来不及打开调试工具,如:
function say(word) { console.log(word); } function execute(someFunction, value) { someFunction(value); } execute(say, "Hello");
进入调试
node --inspect-brk=9229 test.js
--inspect-brk
指定在第一行就设置断点
chrome://inspect
点击继续运行,在console面板输出Hello结束