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

运行 util 格式化、异步互转、类型检测、原型继承与弃用警告实验

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-util.mjs
explore-util.mjs258 行
import util from 'node:util';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';

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

// Case 1: util.format, util.inspect, custom inspect, isDeepStrictEqual, getSystemErrorName
function testFormatAndInspect() {
  const formatted = util.format('Name: %s, Age: %d, Meta: %j', 'Alice', 25, { ok: true });
  const obj = { a: 1, b: 2, c: { d: 3 } };
  const inspected = util.inspect(obj, { showHidden: false, depth: null, colors: false });

  class Tag {
    constructor(label) {
      this.label = label;
    }
    [util.inspect.custom]() {
      return `<Tag:${this.label}>`;
    }
  }
  const customOut = util.inspect(new Tag('v24'));

  let enoentName = null;
  try {
    fs.readFileSync(path.join(os.tmpdir(), `mbsky-nonexistent-${process.pid}-${Date.now()}.txt`));
  } catch (err) {
    enoentName = util.getSystemErrorName(err.errno);
  }

  const expected = {
    formatted: 'Name: Alice, Age: 25, Meta: {"ok":true}',
    inspected: '{ a: 1, b: 2, c: { d: 3 } }',
    customOut: '<Tag:v24>',
    deepEqualSame: true,
    deepEqualDiffType: false,
    enoentName: 'ENOENT',
  };
  const actual = {
    formatted,
    inspected,
    customOut,
    deepEqualSame: util.isDeepStrictEqual({ x: [1, 2] }, { x: [1, 2] }),
    deepEqualDiffType: util.isDeepStrictEqual({ x: 1 }, { x: '1' }),
    enoentName,
  };
  return makeCase('util_format_and_inspect', expected, actual);
}

// Case 2: util.promisify & util.callbackify (including null rejection wrapping)
async function testPromisifyAndCallbackify() {
  const tmpFile = path.join(os.tmpdir(), `mbsky-util-${process.pid}-${Date.now()}.txt`);
  fs.writeFileSync(tmpFile, 'promisify-content', 'utf8');
  const readFileAsync = util.promisify(fs.readFile);
  let readText = '';
  try {
    readText = await readFileAsync(tmpFile, 'utf8');
  } finally {
    fs.unlinkSync(tmpFile);
  }

  async function fnOk() {
    return 'hello world';
  }
  const cbOk = util.callbackify(fnOk);
  const okRes = await new Promise((resolve, reject) => {
    cbOk((err, ret) => (err ? reject(err) : resolve(ret)));
  });

  function fnRejectNull() {
    return Promise.reject(null);
  }
  const cbNull = util.callbackify(fnRejectNull);
  const nullRejectInfo = await new Promise((resolve) => {
    cbNull((err) => {
      resolve({
        isError: err instanceof Error,
        hasReasonProp: Object.prototype.hasOwnProperty.call(err, 'reason'),
        reasonIsNull: err.reason === null,
      });
    });
  });

  const expected = {
    readText: 'promisify-content',
    okRes: 'hello world',
    nullRejectInfo: {
      isError: true,
      hasReasonProp: true,
      reasonIsNull: true,
    },
  };
  const actual = { readText, okRes, nullRejectInfo };
  return makeCase('util_promisify_and_callbackify', expected, actual);
}

// Case 3: util.types predicates and Node v24 status of legacy util.isArray / isRegExp / isDate
function testTypesAndLegacyChecks() {
  const ab = new ArrayBuffer(8);
  const sab = new SharedArrayBuffer(8);
  const bi64 = new BigInt64Array(1);
  const bu64 = new BigUint64Array(1);
  const dv = new DataView(ab);
  async function sampleAsync() {}
  function* sampleGen() {
    yield 1;
  }

  const expected = {
    isAnyArrayBufferAB: true,
    isAnyArrayBufferSAB: true,
    isArrayBuffer: true,
    isAsyncFunction: true,
    isBigInt64Array: true,
    isBigUint64Array: true,
    isBooleanObject: true,
    isDataView: true,
    isDate: true,
    isDateString: false,
    isGeneratorFunction: true,
    isMap: true,
    isSet: true,
    isRegExp: true,
    isSymbolObject: true,
    legacyIsArrayType: 'function',
    legacyIsArrayTrue: true,
    legacyIsArrayFalse: false,
    legacyIsRegExpType: 'undefined',
    legacyIsDateType: 'undefined',
  };
  const actual = {
    isAnyArrayBufferAB: util.types.isAnyArrayBuffer(ab),
    isAnyArrayBufferSAB: util.types.isAnyArrayBuffer(sab),
    isArrayBuffer: util.types.isArrayBuffer(ab),
    isAsyncFunction: util.types.isAsyncFunction(sampleAsync),
    isBigInt64Array: util.types.isBigInt64Array(bi64),
    isBigUint64Array: util.types.isBigUint64Array(bu64),
    isBooleanObject: util.types.isBooleanObject(new Boolean(true)),
    isDataView: util.types.isDataView(dv),
    isDate: util.types.isDate(new Date()),
    isDateString: util.types.isDate(Date()),
    isGeneratorFunction: util.types.isGeneratorFunction(sampleGen),
    isMap: util.types.isMap(new Map()),
    isSet: util.types.isSet(new Set()),
    isRegExp: util.types.isRegExp(/abc/),
    isSymbolObject: util.types.isSymbolObject(Object(Symbol('s'))),
    legacyIsArrayType: typeof util.isArray,
    legacyIsArrayTrue: util.isArray([]),
    legacyIsArrayFalse: util.isArray({}),
    legacyIsRegExpType: typeof util.isRegExp,
    legacyIsDateType: typeof util.isDate,
  };
  return makeCase('util_types_and_legacy_checks', expected, actual);
}

// Case 4: util.inherits prototype-only inheritance vs ES6 class extends
function testInheritsBehavior() {
  function Base() {
    this.name = 'base';
    this.base = 1991;
    this.sayHello = function () {
      return `Hello ${this.name}`;
    };
  }
  Base.prototype.showName = function () {
    return this.name;
  };
  function Sub() {
    this.name = 'sub';
  }
  util.inherits(Sub, Base);

  const objBase = new Base();
  const objSub = new Sub();

  class ModernBase {
    constructor(name = 'base') {
      this.name = name;
      this.base = 1991;
    }
    showName() {
      return this.name;
    }
  }
  class ModernSub extends ModernBase {
    constructor() {
      super('sub');
    }
  }
  const modernSub = new ModernSub();

  const expected = {
    baseShowName: 'base',
    baseSayHello: 'Hello base',
    subShowName: 'sub',
    subOwnKeys: ['name'],
    subHasBaseProp: false,
    subHasSayHello: false,
    subInstanceOfBase: true,
    modernSubBaseProp: 1991,
    modernSubShowName: 'sub',
  };
  const actual = {
    baseShowName: objBase.showName(),
    baseSayHello: objBase.sayHello(),
    subShowName: objSub.showName(),
    subOwnKeys: Object.keys(objSub),
    subHasBaseProp: 'base' in objSub,
    subHasSayHello: typeof objSub.sayHello === 'function',
    subInstanceOfBase: objSub instanceof Base,
    modernSubBaseProp: modernSub.base,
    modernSubShowName: modernSub.showName(),
  };
  return makeCase('util_inherits_behavior', expected, actual);
}

// Case 5: util.deprecate emits DeprecationWarning in isolated child process
function testDeprecateWarning() {
  const childCode = `
    const util = require('node:util');
    let captured = null;
    process.on('warning', (w) => { captured = { name: w.name, message: w.message, code: w.code }; });
    const oldFn = util.deprecate(() => 'ran-old', 'oldFn is deprecated', 'DEP_MBSKY_01');
    const ret = oldFn();
    setImmediate(() => console.log(JSON.stringify({ ret, captured })));
  `;
  const raw = execFileSync(process.execPath, ['--no-warnings', '-e', childCode], { encoding: 'utf8' }).trim();
  const parsed = JSON.parse(raw);

  const expected = {
    ret: 'ran-old',
    captured: {
      name: 'DeprecationWarning',
      message: 'oldFn is deprecated',
      code: 'DEP_MBSKY_01',
    },
  };
  return makeCase('util_deprecate_warning', expected, parsed);
}

const cases = [
  testFormatAndInspect(),
  await testPromisifyAndCallbackify(),
  testTypesAndLegacyChecks(),
  testInheritsBehavior(),
  testDeprecateWarning(),
];

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

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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