Node.js 构建简单应用
按工程步骤演练从零构建一个 Node.js HTTP 应用:环境检查、目录与 package.json 初始化、UTF-8 中文 HTML 响应服务以及基础路径路由,并附 Node.js v24.22.3 实测验证。
学完这一章,你能够
- 按工程步骤演练从零构建一个 Node.js HTTP 应用:环境检查、目录与 package.json 初始化、UTF-8 中文 HTML 响应服务以及基础路径路由,并附 Node.js v24.22.3 实测验证。
环境校验、目录搭建与项目初始化
构建一个最简 Node.js Web 应用可拆解为五个连贯阶段:确认运行环境已安装 Node.js、建立项目目录、初始化 `package.json`、编写 HTTP 服务器入口文件,以及按请求路径返回对应响应。
首先在终端执行 `node -v` 与 `npm -v` 校验工具链(若尚未安装需先完成环境配置;本站离线脚本实测本地运行时版本为 `v24.22.3` 且可执行路径有效)。接着创建项目文件夹 `my-first-node-app` 并进入目录,运行 `npm init -y` 生成 `package.json`,将入口字段 `main` 设为 `app.js` 并在 `scripts` 中配置 `"start": "node app.js"`,最后在根目录新建入口文件 `app.js`。本站实测在临时目录生成并解析该 `package.json` 结构完整无误。
编写 UTF-8 HTML 服务器与添加路径路由
在 `app.js` 中导入 `http` 模块并调用 `http.createServer((req, res) => ...)`:输出中文页面时必须设置响应头 `'Content-Type': 'text/html; charset=utf-8'` 防止浏览器乱码,再通过 `res.end()` 发送 HTML 内容并调用 `server.listen(3000, ...)` 启动监听。通过 `npm start` 启动后控制台打印监听地址,访问 `http://localhost:3000` 即可看到中文欢迎页——本站回环服务实测返回 `200`、精确响应头 `'text/html; charset=utf-8'` 及完整中文 HTML 正文。
为支持多页面访问,可在请求回调中按 `req.url` 分支分发:根路径 `/` 返回 `'Welcome to the homepage!'`、`/about` 返回 `'This is the about page.'`、其他未匹配路径返回状态码 `404` 与 `'404 Not Found'`(本站实测三条路径全部命中预期状态码与文本)。以此为骨架,后续可自然接入数据库驱动或 Express 等框架扩展成完整后端项目。
运行 Node.js 简易应用目录初始化、UTF-8 中文 HTML 服务与基础路由实验
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
function makeCase(name, expected, actual) {
return {
name,
passed: JSON.stringify(expected) === JSON.stringify(actual),
expected,
actual,
};
}
// Case 1: project directory + package.json initialization verification
function testProjectScaffold() {
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mbsky-app-'));
const appDir = path.join(baseDir, 'my-first-node-app');
try {
fs.mkdirSync(appDir, { recursive: true });
const pkg = {
name: 'my-first-node-app',
version: '1.0.0',
main: 'app.js',
scripts: { start: 'node app.js' },
dependencies: {},
};
const pkgPath = path.join(appDir, 'package.json');
const appPath = path.join(appDir, 'app.js');
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf8');
fs.writeFileSync(appPath, '// entry placeholder\n', 'utf8');
const loaded = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const expected = {
name: 'my-first-node-app',
main: 'app.js',
startScript: 'node app.js',
files: ['app.js', 'package.json'],
};
const actual = {
name: loaded.name,
main: loaded.main,
startScript: loaded.scripts.start,
files: fs.readdirSync(appDir).sort(),
};
return makeCase('project_scaffold_and_package_json', expected, actual);
} finally {
fs.rmSync(baseDir, { recursive: true, force: true });
}
}
// Case 2: basic HTML UTF-8 HTTP server on 127.0.0.1:0
async function testHtmlUtf8Server() {
const htmlBody = '<h1>Hello, World!</h1><p>这是我的第一个 Node.js 应用。</p>';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(htmlBody);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
try {
const resp = await fetch(`http://127.0.0.1:${port}/`);
const body = await resp.text();
const expected = {
status: 200,
contentType: 'text/html; charset=utf-8',
body: htmlBody,
};
const actual = {
status: resp.status,
contentType: resp.headers.get('content-type'),
body,
};
return makeCase('html_utf8_http_server', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
// Case 3: routed HTTP app (/, /about, 404)
async function testRoutedHttpApp() {
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the homepage!');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is the about page.');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
try {
const rHome = await fetch(`${base}/`);
const rAbout = await fetch(`${base}/about`);
const rNotFound = await fetch(`${base}/unknown`);
const expected = {
home: [200, 'Welcome to the homepage!'],
about: [200, 'This is the about page.'],
notFound: [404, '404 Not Found'],
};
const actual = {
home: [rHome.status, await rHome.text()],
about: [rAbout.status, await rAbout.text()],
notFound: [rNotFound.status, await rNotFound.text()],
};
return makeCase('routed_http_app', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
// Case 4: Node.js runtime presence check
function testRuntimeToolchain() {
const expected = {
versionStartsV24: true,
execPathExists: true,
};
const actual = {
versionStartsV24: process.version.startsWith('v24.'),
execPathExists: fs.existsSync(process.execPath),
};
return makeCase('runtime_toolchain_check', expected, actual);
}
const cases = [
testProjectScaffold(),
await testHtmlUtf8Server(),
await testRoutedHttpApp(),
testRuntimeToolchain(),
];
console.log(JSON.stringify({ version: process.version, cases }));
- 核对临时目录 package.json 与 app.js 结构、127.0.0.1:0 回环 UTF-8 中文 HTML 200 响应、/ 与 /about 与 404 路由分发以及本地 Node.js v24.22.3 工具链。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:8d1a1ce67b033eccade41e45ea2e5262c47412b8749d1874f6ee3a641cadfb5e
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:d31c71b64316ee4117a5e0b0e45cf50ed32ec0ad96ac93db6f996fdea17dfa75
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么向浏览器返回包含中文的 HTML 字符串时,响应头需要显式加上 charset=utf-8?
展开参考解答
若缺少 charset=utf-8,浏览器可能按默认编码(如 ISO-8859-1 或本地系统编码)解码 UTF-8 字节流,导致页面中文显示乱码。