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

对比同步与异步 I/O 顺序、Promise 链、async/await 错误捕获及并发限流流式读取

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-asynchronous.mjs
explore-asynchronous.mjs161 行
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

function deepEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mbsky-node-async-'));

try {
  const sampleFile = path.join(tmpDir, 'example.txt');
  const secondFile = path.join(tmpDir, 'step2.txt');
  const missingFile = path.join(tmpDir, 'does-not-exist.txt');
  const streamFile = path.join(tmpDir, 'stream-data.txt');
  await fsp.writeFile(sampleFile, 'hello-async-node', 'utf8');
  await fsp.writeFile(secondFile, 'step2-payload', 'utf8');
  await fsp.writeFile(streamFile, 'A'.repeat(100), 'utf8');

  // Case 1: Sync vs Async execution order
  const syncOrder = [];
  const syncText = fs.readFileSync(sampleFile, 'utf8');
  syncOrder.push(`sync:${syncText}`);
  syncOrder.push('after_sync');

  const asyncOrder = [];
  await new Promise((resolve, reject) => {
    fs.readFile(sampleFile, 'utf8', (err, data) => {
      if (err) {
        reject(err);
        return;
      }
      asyncOrder.push(`cb:${data}`);
      resolve();
    });
    asyncOrder.push('after_async_dispatch');
  });

  const cbErrCode = await new Promise((resolve) => {
    fs.readFile(missingFile, 'utf8', (err, data) => {
      if (err) {
        resolve({ handled: true, code: err.code, hasData: data !== undefined });
        return;
      }
      resolve({ handled: false, code: null, hasData: true });
    });
  });

  const actual1 = { syncOrder, asyncOrder, cbErrCode };
  const expected1 = {
    syncOrder: ['sync:hello-async-node', 'after_sync'],
    asyncOrder: ['after_async_dispatch', 'cb:hello-async-node'],
    cbErrCode: { handled: true, code: 'ENOENT', hasData: false },
  };

  // Case 2: Promise chain, error propagation, and state immutability
  const immutableResult = await new Promise((resolve, reject) => {
    resolve('settled_once');
    reject(new Error('ignored_rejection'));
    resolve('ignored_second');
  });

  const chainResult = await fsp
    .readFile(sampleFile, 'utf8')
    .then((first) => fsp.readFile(secondFile, 'utf8').then((second) => `${first}|${second}`));

  const promiseErrCode = await fsp
    .readFile(missingFile, 'utf8')
    .then(() => 'unexpected')
    .catch((err) => err.code);

  const actual2 = { immutableResult, chainResult, promiseErrCode };
  const expected2 = {
    immutableResult: 'settled_once',
    chainResult: 'hello-async-node|step2-payload',
    promiseErrCode: 'ENOENT',
  };

  // Case 3: async/await + try/catch error handling
  async function processFiles(targetPath) {
    try {
      const data = await fsp.readFile(targetPath, 'utf8');
      const extra = await fsp.readFile(secondFile, 'utf8');
      return { ok: true, combined: `${data.toUpperCase()}+${extra}` };
    } catch (err) {
      return { ok: false, code: err.code };
    }
  }

  const asyncOk = await processFiles(sampleFile);
  const asyncFail = await processFiles(missingFile);
  const actual3 = { asyncOk, asyncFail };
  const expected3 = {
    asyncOk: { ok: true, combined: 'HELLO-ASYNC-NODE+step2-payload' },
    asyncFail: { ok: false, code: 'ENOENT' },
  };

  // Case 4: Bounded concurrency & streaming large file
  async function runWithConcurrency(items, limit, worker) {
    let active = 0;
    let maxActive = 0;
    const results = new Array(items.length);
    let nextIndex = 0;

    async function runner() {
      while (nextIndex < items.length) {
        const idx = nextIndex++;
        active += 1;
        if (active > maxActive) maxActive = active;
        results[idx] = await worker(items[idx]);
        active -= 1;
      }
    }

    await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => runner()));
    return { maxActive, results };
  }

  const bounded = await runWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => {
    await new Promise((r) => setTimeout(r, 10));
    return n * 10;
  });

  const streamStats = await new Promise((resolve, reject) => {
    let chunks = 0;
    let bytes = 0;
    const rs = fs.createReadStream(streamFile, { highWaterMark: 32 });
    rs.on('data', (chunk) => {
      chunks += 1;
      bytes += chunk.length;
    });
    rs.on('end', () => resolve({ chunks, bytes }));
    rs.on('error', reject);
  });

  const actual4 = {
    maxActive: bounded.maxActive,
    results: bounded.results,
    streamChunks: streamStats.chunks,
    streamBytes: streamStats.bytes,
  };
  const expected4 = {
    maxActive: 2,
    results: [10, 20, 30, 40, 50],
    streamChunks: 4,
    streamBytes: 100,
  };

  const cases = [
    { name: 'sync_vs_async_order', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
    { name: 'promise_chain_and_error', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
    { name: 'async_await_try_catch', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
    { name: 'concurrency_limit_and_stream', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
  ];

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

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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