蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Node.js 简易应用目录初始化、UTF-8 中文 HTML 服务与基础路由实验

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-build-app.mjs
explore-build-app.mjs139 行
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 }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/nodejs-build-app-lab/explore-build-app.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-build-app.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1043.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习