Node.js VS Code
核对 VS Code 开发 Node.js 的核心优势、推荐扩展、项目初始化、HTTP 应用编写运行与 launch.json 断点调试流程,并在本地 Node.js v24.22.3 中实测项目清单、app.js 回环服务与内置 inspector 调试能力。
学完这一章,你能够
- 核对 VS Code 开发 Node.js 的核心优势、推荐扩展、项目初始化、HTTP 应用编写运行与 launch.json 断点调试流程,并在本地 Node.js v24.22.3 中实测项目清单、app.js 回环服务与内置 inspector 调试能力。
VS Code 优势、安装与扩展生态
Visual Studio Code(简称 VS Code)是微软开源的跨平台轻量编辑器,因其内置 JavaScript/Node.js 智能补全与调试支持、丰富的扩展市场、自带集成终端以及低资源占用快启动特性,成为 Node.js 开发的常用工具。
安装时直接前往 VS Code 官网下载对应操作系统安装包并按向导完成即可,系统学习编辑器操作可查阅 VS Code 官方文档。除原生 VS Code 外,业界也存在基于其深度定制的 AI 编程 IDE(如 Qoder、Trae 等,仅作生态工具提及,不带入原页面第三方推广链接与悬停脚本)。
针对 Node.js 工程可按需选用常用扩展:`Node.js Extension Pack` 整合常用开发插件,`JavaScript (ES6) code snippets` 提供语法片段,`Auto Rename Tag` 自动同步修改配对标签,`ESLint` 负责静态代码质量检查,`Prettier` 统一代码格式,`npm Intellisense` 与 `Path Intellisense` 分别补全依赖包名与本地文件路径。
初始化项目与运行第一个 HTTP 服务
在 VS Code 中按 Ctrl + 反引号键呼出集成终端,执行 `mkdir my-node-app && cd my-node-app` 创建并进入工程目录,再运行 `npm init -y` 快速生成默认 `package.json`。本站离线实测在临时目录创建 `my-node-app` 并生成解析标准清单文件,核对 `name` 为 `my-node-app`、`version` 为 `1.0.0`、`main` 为 `app.js`、`license` 为 `ISC`。
接着新建 `app.js`,引入内置 `http` 模块并用 `http.createServer` 返回状态码 `200`、`Content-Type: text/plain` 与纯文本响应体,监听本地端口(如 `3000`)后在终端执行 `node app.js` 并通过浏览器访问 `http://localhost:3000`。本站离线实测启动回环 HTTP 服务并通过原生 `fetch()` 验证返回状态码 `200`、`content-type: text/plain` 及响应体 `Hello, Node.js!\n`。编码期间输入 `console.` 时编辑器的 IntelliSense 会自动列出日志方法;本站实测检查 `console` 上 `log/error/warn/info/table/time/timeEnd` 共 7 个常用成员均为函数。
VS Code 断点调试配置与控制快捷键
VS Code 内置面向 Node.js 的可视化调试器:点击左侧活动栏“运行和调试”图标,选择“创建 `launch.json` 文件”并指定 `Node.js` 环境即可在 `.vscode/launch.json` 中生成启动配置。本站离线实测写入并校验标准 `launch.json`(`version: 0.2.0`、`type: node`、`request: launch`、`program: ${workspaceFolder}/app.js`),同时确认当前 Node.js 运行时内置 `node:inspector` 调试协议接口可用。
配置完成后,在行号左侧单击设下红色断点并按 `F5` 启动调试,随后借助调试工具栏或快捷键掌控执行流:`F5` 继续运行至下一断点,`F10` 单步跳过当前语句不进入函数体,`F11` 单步步入函数内部,`Ctrl+Shift+F5` 重启调试会话,`Shift+F5` 停止调试。
离线验证 Node.js 项目清单、app.js 回环 HTTP 服务、launch.json 调试配置与 console 成员
展开查看收起
import fs from 'node:fs';
import http from 'node:http';
import inspector from 'node:inspector';
import os from 'node:os';
import path from 'node:path';
const cases = [];
// Case 1: project_init_and_package_json
{
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch04-proj-'));
try {
const projectDir = path.join(tmpDir, 'my-node-app');
fs.mkdirSync(projectDir, { recursive: true });
const manifest = {
name: 'my-node-app',
version: '1.0.0',
description: '',
main: 'app.js',
scripts: { test: 'echo "Error: no test specified" && exit 1' },
keywords: [],
author: '',
license: 'ISC',
};
const pkgPath = path.join(projectDir, 'package.json');
fs.writeFileSync(pkgPath, JSON.stringify(manifest, null, 2), 'utf8');
const parsed = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const actual = {
dirExists: fs.existsSync(projectDir),
name: parsed.name,
version: parsed.version,
main: parsed.main,
license: parsed.license,
};
const expected = {
dirExists: true,
name: 'my-node-app',
version: '1.0.0',
main: 'app.js',
license: 'ISC',
};
cases.push({
name: 'project_init_and_package_json',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
// Case 2: http_app_js_loopback_server
{
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, Node.js!\n');
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
const { port } = server.address();
const resp = await fetch(`http://127.0.0.1:${port}/`);
const actual = {
status: resp.status,
contentType: resp.headers.get('content-type'),
body: await resp.text(),
};
const expected = {
status: 200,
contentType: 'text/plain',
body: 'Hello, Node.js!\n',
};
cases.push({
name: 'http_app_js_loopback_server',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
// Case 3: vscode_launch_json_and_inspector
{
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch04-dbg-'));
try {
const vscodeDir = path.join(tmpDir, '.vscode');
fs.mkdirSync(vscodeDir, { recursive: true });
const launchConfig = {
version: '0.2.0',
configurations: [
{
type: 'node',
request: 'launch',
name: 'Launch Program',
skipFiles: ['<node_internals>/**'],
program: '${workspaceFolder}/app.js',
},
],
};
const launchPath = path.join(vscodeDir, 'launch.json');
fs.writeFileSync(launchPath, JSON.stringify(launchConfig, null, 2), 'utf8');
const loaded = JSON.parse(fs.readFileSync(launchPath, 'utf8'));
const cfg = loaded.configurations[0];
const actual = {
schemaVersion: loaded.version,
debugType: cfg.type,
requestMode: cfg.request,
program: cfg.program,
inspectorAvailable: typeof inspector.open === 'function' && typeof inspector.url === 'function',
};
const expected = {
schemaVersion: '0.2.0',
debugType: 'node',
requestMode: 'launch',
program: '${workspaceFolder}/app.js',
inspectorAvailable: true,
};
cases.push({
name: 'vscode_launch_json_and_inspector',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
}
// Case 4: console_api_intellisense_members
{
const members = ['log', 'error', 'warn', 'info', 'table', 'time', 'timeEnd'];
const actual = {
allFunctions: members.every((m) => typeof console[m] === 'function'),
checkedCount: members.length,
};
const expected = {
allFunctions: true,
checkedCount: 7,
};
cases.push({
name: 'console_api_intellisense_members',
passed: JSON.stringify(actual) === JSON.stringify(expected),
expected,
actual,
});
}
console.log(JSON.stringify({ version: process.version, cases }));
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
F10(单步跳过)将当前行的函数调用作为整体执行并停在下一行,适合略过无需深究的辅助函数;F11(单步调试)会进入当前行调用的函数内部逐行跟踪。.vscode/launch.json 用于固化调试器类型(node)、启动入口程序(program)、环境变量及断点跳过规则,便于团队一键复现调试配置。