commandTest.mjs 4.37 KB
import { exec, execSync } from 'node:child_process';

/**
 * 方案 1: 使用 execSync + encoding(推荐)
 * 同步执行,直接获取输出字符串
 */
function testCommandSync() {
  console.log('📡 执行 ipconfig 命令...\n');
  try {
    // 设置 encoding: 'utf8' 来捕获输出
    const output = execSync('ipconfig', {
      encoding: 'utf8', // 将输出转为字符串
      windowsHide: true, // Windows 下隐藏命令窗口
    });

    console.log('✅ 命令执行成功!\n');
    console.log('📋 输出内容:');
    console.log('─'.repeat(60));
    console.log(output);
    console.log('─'.repeat(60));

    return output;
  } catch (error) {
    console.error(`❌ 命令执行失败: ${error.message}`);
    console.error(`错误输出: ${error.stderr || '无'}`);
    process.exit(1);
  }
}

/**
 * 方案 2: 使用 execSync + stdio: 'inherit'
 * 直接将输出显示到终端(实时输出)
 */
function testCommandInherit() {
  console.log('📡 执行 ipconfig 命令(实时输出)...\n');
  try {
    execSync('ipconfig', {
      stdio: 'inherit', // 继承父进程的输入输出
      windowsHide: true,
    });

    console.log('\n✅ 命令执行完成!');
  } catch (error) {
    console.error(`❌ 命令执行失败: ${error.message}`);
    process.exit(1);
  }
}

/**
 * 方案 3: 使用异步 exec(高级用法)
 * 可以同时获取 stdout 和 stderr
 */
function testCommandAsync() {
  return new Promise((resolve, reject) => {
    console.log('📡 执行 ipconfig 命令(异步方式)...\n');

    exec('ipconfig', { encoding: 'utf8' }, (error, stdout, stderr) => {
      if (error) {
        console.error(`❌ 命令执行失败: ${error.message}`);
        console.error(`错误输出: ${stderr}`);
        reject(error);
        return;
      }

      console.log('✅ 命令执行成功!\n');
      console.log('📋 标准输出:');
      console.log('─'.repeat(60));
      console.log(stdout);
      console.log('─'.repeat(60));

      if (stderr) {
        console.log('\n⚠️  错误输出:');
        console.log(stderr);
      }

      resolve(stdout);
    });
  });
}

/**
 * 方案 4: 执行多个命令并格式化输出
 * 获取 IPv4 地址信息
 */
function testCommandWithFilter() {
  console.log('📡 获取网络配置信息...\n');
  try {
    // Windows 下获取详细信息
    const output = execSync('ipconfig', {
      encoding: 'utf8',
      windowsHide: true,
    });

    console.log('✅ 命令执行成功!\n');

    // 解析并格式化输出
    const lines = output.split('\n');
    let currentAdapter = '';

    console.log('🌐 网络适配器信息:');
    console.log('═'.repeat(60));

    lines.forEach((line) => {
      const trimmedLine = line.trim();

      // 检测适配器名称
      if (
        trimmedLine &&
        !trimmedLine.startsWith(' ') &&
        trimmedLine.includes(':')
      ) {
        currentAdapter = trimmedLine;
        console.log(`\n📶 ${currentAdapter}`);
      }

      // IPv4 地址
      if (trimmedLine.includes('IPv4')) {
        console.log(`   ├─ ${trimmedLine}`);
      }

      // 子网掩码
      if (
        trimmedLine.includes('子网掩码') ||
        trimmedLine.includes('Subnet Mask')
      ) {
        console.log(`   ├─ ${trimmedLine}`);
      }

      // 默认网关
      if (
        trimmedLine.includes('默认网关') ||
        trimmedLine.includes('Default Gateway')
      ) {
        console.log(`   └─ ${trimmedLine}`);
      }
    });

    console.log(`\n${'═'.repeat(60)}`);

    return output;
  } catch (error) {
    console.error(`❌ 命令执行失败: ${error.message}`);
    process.exit(1);
  }
}

/**
 * 测试命令函数
 * 可以选择不同的方案
 */
function testCommand() {
  console.log('🚀 开始测试命令执行\n');

  // 选择你想要的方案(取消注释对应的方案)

  // 方案 1: 同步获取输出(推荐)✅
  testCommandSync();

  // 方案 2: 实时显示输出
  // testCommandInherit();

  // 方案 3: 异步方式(需要在 main 中使用 await)
  // return testCommandAsync();

  // 方案 4: 格式化输出
  // testCommandWithFilter();
}

async function main() {
  try {
    await testCommand();
    console.log('\n✨ 测试完成!');
  } catch (error) {
    console.error(`❌ 测试过程中出现错误: ${error.message}`);
    process.exit(1);
  }
}

// 执行主函数
main();