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

离线实测非阻塞 I/O、事件循环、模块全局作用域、Worker Threads 与 REST 路由模式

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-intro.mjs
explore-intro.mjs306 行
import fs from 'node:fs';
import http from 'node:http';
import { createRequire } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { Worker, isMainThread } from 'node:worker_threads';

const cases = [];

// Case 1: blocking_vs_nonblocking_io
{
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch02-io-'));
  try {
    const files = ['file1.txt', 'file2.txt', 'file3.txt'].map((name, idx) => {
      const p = path.join(tmpDir, name);
      fs.writeFileSync(p, `content-${idx + 1}`, 'utf8');
      return p;
    });
    const syncData = files.map((p) => fs.readFileSync(p, 'utf8'));
    const timeline = [];
    const asyncRead = Promise.all(
      files.map((p) =>
        fs.promises.readFile(p, 'utf8').then((txt) => {
          timeline.push('async-done');
          return txt;
        })
      )
    );
    timeline.push('sync-after-dispatch');
    const asyncData = await asyncRead;
    const actual = {
      syncData,
      asyncData,
      firstTimelineEvent: timeline[0],
      asyncCompletedCount: timeline.filter((e) => e === 'async-done').length,
    };
    const expected = {
      syncData: ['content-1', 'content-2', 'content-3'],
      asyncData: ['content-1', 'content-2', 'content-3'],
      firstTimelineEvent: 'sync-after-dispatch',
      asyncCompletedCount: 3,
    };
    cases.push({
      name: 'blocking_vs_nonblocking_io',
      passed: JSON.stringify(actual) === JSON.stringify(expected),
      expected,
      actual,
    });
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

// Case 2: event_loop_and_global_scope
{
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodejs-ch02-scope-'));
  try {
    const markerFile = path.join(tmpDir, 'probe.txt');
    fs.writeFileSync(markerFile, 'ok', 'utf8');
    const phaseOrder = await new Promise((resolve, reject) => {
      fs.readFile(markerFile, 'utf8', (err) => {
        if (err) return reject(err);
        const seq = [];
        setTimeout(() => {
          seq.push('timers');
          resolve(seq);
        }, 0);
        setImmediate(() => {
          seq.push('check');
        });
        Promise.resolve().then(() => {
          seq.push('microtask');
        });
      });
    });

    const cjsFile = path.join(tmpDir, 'scope-check.cjs');
    fs.writeFileSync(
      cjsFile,
      [
        "var localVar = 'hello';",
        'module.exports = {',
        '  thisIsGlobal: this === global,',
        '  thisIsExports: this === exports,',
        '  varOnGlobal: typeof global.localVar,',
        '  hasDirname: typeof __dirname === "string" && __dirname.length > 0,',
        '  hasFilename: typeof __filename === "string" && __filename.endsWith("scope-check.cjs"),',
        '};',
      ].join('\n'),
      'utf8'
    );
    const req = createRequire(import.meta.url);
    const cjsProbe = req(cjsFile);

    const actual = {
      phaseOrder,
      hasGlobal: typeof global === 'object' && globalThis === global,
      hasWindow: typeof globalThis.window !== 'undefined',
      hasDocument: typeof globalThis.document !== 'undefined',
      hasBuffer: typeof Buffer === 'function',
      hasProcess: typeof process === 'object' && typeof process.env === 'object',
      cjsProbe,
    };
    const expected = {
      phaseOrder: ['microtask', 'check', 'timers'],
      hasGlobal: true,
      hasWindow: false,
      hasDocument: false,
      hasBuffer: true,
      hasProcess: true,
      cjsProbe: {
        thisIsGlobal: false,
        thisIsExports: true,
        varOnGlobal: 'undefined',
        hasDirname: true,
        hasFilename: true,
      },
    };
    cases.push({
      name: 'event_loop_and_global_scope',
      passed: JSON.stringify(actual) === JSON.stringify(expected),
      expected,
      actual,
    });
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

// Case 3: http_concurrency_and_shared_validation
{
  function validateEmail(email) {
    const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return regex.test(email);
  }

  const server = http.createServer((req, res) => {
    setTimeout(() => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Hello World\n');
    }, 10);
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const { port } = server.address();
    const responses = await Promise.all(
      Array.from({ length: 5 }, () =>
        fetch(`http://127.0.0.1:${port}/`).then(async (r) => ({
          status: r.status,
          body: await r.text(),
        }))
      )
    );
    const actual = {
      validEmail: validateEmail('dev@example.com'),
      invalidEmail: validateEmail('bad-email@'),
      concurrentCount: responses.length,
      allOk: responses.every((r) => r.status === 200 && r.body === 'Hello World\n'),
    };
    const expected = {
      validEmail: true,
      invalidEmail: false,
      concurrentCount: 5,
      allOk: true,
    };
    cases.push({
      name: 'http_concurrency_and_shared_validation',
      passed: JSON.stringify(actual) === JSON.stringify(expected),
      expected,
      actual,
    });
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
}

// Case 4: worker_threads_cpu_offload
{
  const workerResult = await new Promise((resolve, reject) => {
    const worker = new Worker(
      `
        const { parentPort, workerData } = require('node:worker_threads');
        function fibonacciSync(n) {
          if (n < 2) return n;
          return fibonacciSync(n - 1) + fibonacciSync(n - 2);
        }
        parentPort.postMessage(fibonacciSync(workerData.n));
      `,
      { eval: true, workerData: { n: 20 } }
    );
    worker.on('message', resolve);
    worker.on('error', reject);
  });

  const actual = {
    isMainThread,
    fib20: workerResult,
  };
  const expected = {
    isMainThread: true,
    fib20: 6765,
  };
  cases.push({
    name: 'worker_threads_cpu_offload',
    passed: JSON.stringify(actual) === JSON.stringify(expected),
    expected,
    actual,
  });
}

// Case 5: async_await_and_rest_api_pattern
{
  const users = [
    { id: 1, name: '张三' },
    { id: 2, name: '李四' },
  ];
  const apiServer = http.createServer((req, res) => {
    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => {
      const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null;
      if (req.method === 'GET' && req.url === '/api/users') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(users));
      } else if (req.method === 'POST' && req.url === '/api/users') {
        res.writeHead(201, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: '用户创建成功', user: body }));
      } else if (req.method === 'PUT' && req.url === '/api/users/1') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: '用户 1 更新成功', data: body }));
      } else if (req.method === 'DELETE' && req.url === '/api/users/1') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ message: '用户 1 删除成功' }));
      } else {
        res.writeHead(404);
        res.end('Not Found');
      }
    });
  });

  const noop = () => {};
  process.on('uncaughtException', noop);
  const uncaughtListeners = process.listenerCount('uncaughtException');
  process.off('uncaughtException', noop);

  await new Promise((resolve) => apiServer.listen(0, '127.0.0.1', resolve));
  try {
    const base = `http://127.0.0.1:${apiServer.address().port}`;
    const getList = await (await fetch(`${base}/api/users`)).json();
    const postRes = await fetch(`${base}/api/users`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: 3, name: '王五' }),
    });
    const postJson = await postRes.json();
    const putJson = await (
      await fetch(`${base}/api/users/1`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: '张三-更新' }),
      })
    ).json();
    const delJson = await (await fetch(`${base}/api/users/1`, { method: 'DELETE' })).json();

    const rewrittenPath = '/api/users'.replace(/^\/api/, '');
    let missingCaught = false;
    try {
      await fs.promises.readFile(path.join(os.tmpdir(), 'definitely-missing-ch02.txt'));
    } catch (err) {
      missingCaught = err.code === 'ENOENT';
    }

    const actual = {
      getCount: getList.length,
      postStatus: postRes.status,
      postCreatedName: postJson.user.name,
      putMessage: putJson.message,
      deleteMessage: delJson.message,
      rewrittenPath,
      missingCaught,
      hookRegistered: uncaughtListeners >= 1,
    };
    const expected = {
      getCount: 2,
      postStatus: 201,
      postCreatedName: '王五',
      putMessage: '用户 1 更新成功',
      deleteMessage: '用户 1 删除成功',
      rewrittenPath: '/users',
      missingCaught: true,
      hookRegistered: true,
    };
    cases.push({
      name: 'async_await_and_rest_api_pattern',
      passed: JSON.stringify(actual) === JSON.stringify(expected),
      expected,
      actual,
    });
  } finally {
    await new Promise((resolve) => apiServer.close(resolve));
  }
}

console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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