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

运行全局对象作用域、定时器生命周期、Console 流输出与 Process 进程实验

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-global-object.mjs
explore-global-object.mjs203 行
import path from 'node:path';
import { Console } from 'node:console';
import { PassThrough } from 'node:stream';
import { execFileSync } from 'node:child_process';

function makeCase(name, expected, actual) {
  return {
    name,
    passed: JSON.stringify(expected) === JSON.stringify(actual),
    expected,
    actual,
  };
}

// Case 1: global/globalThis, module scope isolation, and import.meta.filename/dirname
function testGlobalAndModulePaths() {
  const moduleScopedVar = 'isolated-in-module';
  globalThis.__mbskyGlobalMarker = 'global-visible';
  const viaGlobal = global.__mbskyGlobalMarker;
  delete globalThis.__mbskyGlobalMarker;

  const expected = {
    globalEqualsGlobalThis: true,
    moduleVarNotOnGlobal: true,
    explicitGlobalVisible: 'global-visible',
    cleanedUp: true,
    fileBase: 'explore-global-object.mjs',
    dirMatchesParent: true,
    isAbsolute: true,
  };
  const actual = {
    globalEqualsGlobalThis: global === globalThis,
    moduleVarNotOnGlobal: typeof globalThis.moduleScopedVar === 'undefined' && moduleScopedVar === 'isolated-in-module',
    explicitGlobalVisible: viaGlobal,
    cleanedUp: !('__mbskyGlobalMarker' in globalThis),
    fileBase: path.basename(import.meta.filename),
    dirMatchesParent: import.meta.dirname === path.dirname(import.meta.filename),
    isAbsolute: path.isAbsolute(import.meta.filename),
  };
  return makeCase('global_and_module_paths', expected, actual);
}

// Case 2: setTimeout, clearTimeout, setInterval, clearInterval
async function testTimersLifecycle() {
  let canceledRan = false;
  const t = setTimeout(() => {
    canceledRan = true;
  }, 15);
  clearTimeout(t);

  const onceResult = await new Promise((resolve) => {
    setTimeout(() => resolve('fired-once'), 25);
  });

  const ticks = [];
  await new Promise((resolve) => {
    const iv = setInterval(() => {
      ticks.push(ticks.length + 1);
      if (ticks.length === 3) {
        clearInterval(iv);
        resolve();
      }
    }, 10);
  });

  const expected = {
    onceResult: 'fired-once',
    canceledRan: false,
    intervalTicks: [1, 2, 3],
  };
  const actual = {
    onceResult,
    canceledRan,
    intervalTicks: ticks,
  };
  return makeCase('timers_lifecycle', expected, actual);
}

// Case 3: console formatting, streams, time/timeEnd, assert, trace
function testConsoleFormattingAndStreams() {
  const outBuf = [];
  const errBuf = [];
  const outStream = new PassThrough();
  const errStream = new PassThrough();
  outStream.on('data', (c) => outBuf.push(c.toString('utf8')));
  errStream.on('data', (c) => errBuf.push(c.toString('utf8')));

  const c = new Console({ stdout: outStream, stderr: errStream, colorMode: false });
  c.log('Hello world');
  c.log('byvoid%diovyb');
  c.log('byvoid%diovyb', 1991);
  c.info('counter: %d', 10);
  c.time('fetch');
  c.timeEnd('fetch');
  c.dir({ a: 1 });
  c.error('err-line');
  c.warn('warn-line');
  c.assert(true, 'should-not-appear');
  c.assert(false, 'assert-triggered');
  c.trace('stack-marker');

  const outText = outBuf.join('');
  const errText = errBuf.join('');

  const expected = {
    hasPlainLog: true,
    hasUnfilledFormat: true,
    hasFilledFormat: true,
    hasInfoCount: true,
    hasTimerLine: true,
    hasDirObject: true,
    hasErrorLine: true,
    hasWarnLine: true,
    trueAssertSilent: true,
    falseAssertLogged: true,
    hasTraceHeader: true,
  };
  const actual = {
    hasPlainLog: outText.includes('Hello world\n'),
    hasUnfilledFormat: outText.includes('byvoid%diovyb\n'),
    hasFilledFormat: outText.includes('byvoid1991iovyb\n'),
    hasInfoCount: outText.includes('counter: 10\n'),
    hasTimerLine: /fetch:\s*\d+(\.\d+)?m?s/.test(outText),
    hasDirObject: outText.includes('{ a: 1 }'),
    hasErrorLine: errText.includes('err-line'),
    hasWarnLine: errText.includes('warn-line'),
    trueAssertSilent: !errText.includes('should-not-appear'),
    falseAssertLogged: errText.includes('assert-triggered'),
    hasTraceHeader: errText.includes('Trace: stack-marker'),
  };
  return makeCase('console_formatting_and_streams', expected, actual);
}

// Case 4: process properties, methods, nextTick order, and child exit event
async function testProcessInfoAndEvents() {
  const mem = process.memoryUsage();
  const hrStart = process.hrtime();
  const hrDiff = process.hrtime(hrStart);

  const order = [];
  await new Promise((resolve) => {
    setTimeout(() => {
      order.push('timeout');
      resolve();
    }, 0);
    process.nextTick(() => {
      order.push('nextTick');
    });
  });

  const childScript = `
    process.on('exit', (code) => {
      setTimeout(() => console.log('NEVER'), 0);
      console.log('EXIT_CODE:' + code);
    });
    console.log('MAIN_DONE');
  `;
  const childOut = execFileSync(process.execPath, ['-e', childScript], { encoding: 'utf8' })
    .trim()
    .split(/\r?\n/);

  const expected = {
    versionMajor24: true,
    hasVersionsNode: true,
    argvHasAtLeast2: true,
    execPathNonEmpty: true,
    cwdIsAbsolute: true,
    pidPositiveInt: true,
    hasValidPlatform: true,
    hasValidArch: true,
    memHasCoreKeys: true,
    hrtimeIsPair: true,
    uptimeNonNegative: true,
    tickBeforeTimeout: ['nextTick', 'timeout'],
    childExitLines: ['MAIN_DONE', 'EXIT_CODE:0'],
  };
  const actual = {
    versionMajor24: process.version.startsWith('v24.'),
    hasVersionsNode: typeof process.versions.node === 'string' && process.versions.node.length > 0,
    argvHasAtLeast2: Array.isArray(process.argv) && process.argv.length >= 2,
    execPathNonEmpty: typeof process.execPath === 'string' && process.execPath.length > 0,
    cwdIsAbsolute: path.isAbsolute(process.cwd()),
    pidPositiveInt: Number.isInteger(process.pid) && process.pid > 0,
    hasValidPlatform: ['win32', 'linux', 'darwin', 'freebsd', 'sunos'].includes(process.platform),
    hasValidArch: typeof process.arch === 'string' && process.arch.length > 0,
    memHasCoreKeys: mem.rss > 0 && mem.heapTotal > 0 && mem.heapUsed > 0,
    hrtimeIsPair: Array.isArray(hrDiff) && hrDiff.length === 2 && hrDiff[0] >= 0 && hrDiff[1] >= 0,
    uptimeNonNegative: process.uptime() >= 0,
    tickBeforeTimeout: order,
    childExitLines: childOut,
  };
  return makeCase('process_info_and_events', expected, actual);
}

const cases = [
  testGlobalAndModulePaths(),
  await testTimersLifecycle(),
  testConsoleFormattingAndStreams(),
  await testProcessInfoAndEvents(),
];

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

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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