如何检查当前目录是否运行tsc --watch?实现自动启动脚本
检查
tsc --watch进程并按需启动的实现方案 没问题!我来给你分享几个实用的检查方法,不管你是用Linux/macOS还是Windows,都能完美适配你的需求:
Linux/macOS(类Unix系统)
在类Unix系统里,我们可以用ps结合grep来过滤进程,还要注意排除grep自身的进程干扰。
核心检查命令
ps aux | grep "tsc --watch" | grep -v grep
如果输出为空,说明没有tsc --watch在运行;反之则已有进程。
完整bash脚本示例
#!/bin/bash # 静默检查进程是否存在 if ! ps aux | grep "tsc --watch" | grep -v grep > /dev/null; then # 这里替换成你常用的终端命令,比如gnome-terminal、iTerm2等 # 以gnome-terminal为例,启动后保持窗口打开 gnome-terminal -- bash -c "tsc --watch; exec bash" echo "已启动新的tsc --watch进程" else echo "tsc --watch 已经在运行啦!" fi
Windows系统
Windows下tsc是通过node.exe运行的,所以我们需要找带有tsc --watch参数的node进程,用tasklist和findstr组合实现。
核心检查命令
tasklist /FI "IMAGENAME eq node.exe" /V | findstr /I "tsc --watch"
完整批处理脚本示例
@echo off :: 静默检查进程 tasklist /FI "IMAGENAME eq node.exe" /V | findstr /I "tsc --watch" > nul if %errorlevel% equ 1 ( :: 打开新CMD窗口并启动tsc --watch,/k参数让窗口保持打开 start cmd /k "tsc --watch" echo 已启动新的tsc --watch进程 ) else ( echo tsc --watch 已经在运行中! )
跨平台方案(Node.js脚本)
如果你本身就在Node项目中,写个Node脚本更省心,自动适配不同系统:
const { exec } = require('child_process'); const { spawn } = require('child_process'); // 封装进程检查函数 async function isTscWatchRunning() { let command; if (process.platform === 'win32') { command = 'tasklist /FI "IMAGENAME eq node.exe" /V | findstr /I "tsc --watch"'; } else { command = 'ps aux | grep "tsc --watch" | grep -v grep'; } const { stdout } = await new Promise((res) => exec(command, (err, out) => res({ stdout: out || '' }))); return stdout.trim() !== ''; } // 主逻辑 async function main() { const running = await isTscWatchRunning(); if (!running) { let terminalCmd, terminalArgs; switch (process.platform) { case 'win32': terminalCmd = 'cmd.exe'; terminalArgs = ['/k', 'tsc --watch']; break; case 'darwin': // macOS terminalCmd = 'open'; terminalArgs = ['-a', 'Terminal', '--args', '-c', 'tsc --watch']; break; default: // Linux terminalCmd = 'gnome-terminal'; terminalArgs = ['--', 'bash', '-c', 'tsc --watch; exec bash']; } // 启动独立终端进程,避免主脚本关闭影响 spawn(terminalCmd, terminalArgs, { detached: true, stdio: 'ignore' }).unref(); console.log('✅ 已启动tsc --watch'); } else { console.log('ℹ️ tsc --watch已在运行'); } } main();
内容的提问来源于stack exchange,提问作者Suhair Zain
相关产品推荐
相关产品推荐

