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

在 Node.js v24 中核验 Electron 三层组成、记事本窗口生命周期与启动命令契约

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-tutorial.mjs
explore-tutorial.mjs154 行
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

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

const cases = [];

// Case 1: Node.js runtime baseline & HTML/CSS selector basics
{
  const nodeMajor = Number(process.versions.node.split('.')[0]);
  const selectors = ['#id', '.class'].map((sel) => ({
    selector: sel,
    type: sel.startsWith('#') ? 'id' : sel.startsWith('.') ? 'class' : 'tag',
    name: sel.slice(1),
  }));
  const notepadHtml = '<h1>我的桌面记事本</h1>\n<textarea></textarea>';
  const hasH1 = /<h1>[\s\S]*<\/h1>/.test(notepadHtml);
  const hasTextarea = /<textarea><\/textarea>/.test(notepadHtml);

  const expected = {
    nodeMajorAtLeast20: true,
    hasV8Engine: true,
    selectors: [
      { selector: '#id', type: 'id', name: 'id' },
      { selector: '.class', type: 'class', name: 'class' },
    ],
    notepadHasH1: true,
    notepadHasTextarea: true,
  };
  const actual = {
    nodeMajorAtLeast20: nodeMajor >= 20,
    hasV8Engine: typeof process.versions.v8 === 'string' && process.versions.v8.length > 0,
    selectors,
    notepadHasH1: hasH1,
    notepadHasTextarea: hasTextarea,
  };
  cases.push(makeCase('node_runtime_and_selector_basics', expected, actual));
}

// Case 2: Electron composition & cross-platform target artifacts
{
  const stack = [
    { layer: 'Chromium', role: 'renderer_ui' },
    { layer: 'Node.js', role: 'system_api' },
    { layer: 'Native APIs', role: 'os_integration' },
  ];
  const targetMap = {
    win32: '.exe',
    darwin: '.app',
    linux: 'AppImage/executable',
  };
  const expected = {
    layers: ['Chromium', 'Node.js', 'Native APIs'],
    targets: { win32: '.exe', darwin: '.app', linux: 'AppImage/executable' },
    sharedCodebasePlatforms: 3,
  };
  const actual = {
    layers: stack.map((item) => item.layer),
    targets: targetMap,
    sharedCodebasePlatforms: Object.keys(targetMap).length,
  };
  cases.push(makeCase('electron_composition_and_cross_platform_targets', expected, actual));
}

// Case 3: Notepad BrowserWindow creation and local HTML file loading contract
{
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'electron-ch01-'));
  try {
    const htmlPath = path.join(tmpDir, 'index.html');
    fs.writeFileSync(htmlPath, '<h1>我的桌面记事本</h1>\n<textarea></textarea>', 'utf8');

    const app = new EventEmitter();
    app.whenReady = () =>
      new Promise((resolve) => {
        app.once('ready', resolve);
      });

    class MockBrowserWindow {
      constructor(opts) {
        this.width = opts.width;
        this.height = opts.height;
        this.loadedFile = null;
        this.htmlLength = 0;
      }
      loadFile(relPath) {
        const full = path.join(tmpDir, relPath);
        const content = fs.readFileSync(full, 'utf8');
        this.loadedFile = path.basename(full);
        this.htmlLength = content.length;
      }
    }

    let createdWindow = null;
    const readyPromise = app.whenReady().then(() => {
      createdWindow = new MockBrowserWindow({ width: 800, height: 600 });
      createdWindow.loadFile('index.html');
    });

    app.emit('ready');
    await readyPromise;

    const expected = {
      width: 800,
      height: 600,
      loadedFile: 'index.html',
      htmlByteCheck: true,
    };
    const actual = {
      width: createdWindow.width,
      height: createdWindow.height,
      loadedFile: createdWindow.loadedFile,
      htmlByteCheck: createdWindow.htmlLength > 20,
    };
    cases.push(makeCase('notepad_main_window_lifecycle', expected, actual));
  } finally {
    fs.rmSync(tmpDir, { recursive: true, force: true });
  }
}

// Case 4: CLI install & startup command contract
{
  const installCmd = 'npm install electron';
  const startCmd = 'npx electron .';
  const manifest = {
    name: 'electron-notepad-demo',
    main: 'main.js',
    scripts: { start: 'electron .' },
  };
  const expected = {
    installPackage: 'electron',
    runTarget: '.',
    mainEntry: 'main.js',
    startScript: 'electron .',
  };
  const actual = {
    installPackage: installCmd.split(/\s+/).at(-1),
    runTarget: startCmd.split(/\s+/).at(-1),
    mainEntry: manifest.main,
    startScript: manifest.scripts.start,
  };
  cases.push(makeCase('cli_startup_contract', expected, actual));
}

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

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

入口文件:projects/electron-tutorial-lab/explore-tutorial.mjs

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

下载课程关联工程包:Electron

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

下载课程关联工程包:Electron

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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