fix: 修复在windows环境下 pm2执行失败,找不到bun的问题
This commit is contained in:
74
assistant/src/module/get-bun-path.ts
Normal file
74
assistant/src/module/get-bun-path.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
export const getBunPath = (): string => {
|
||||
// 在不同平台上获取 bun 可执行文件的路径
|
||||
const isWindows = process.platform === 'win32';
|
||||
const bunExecutableName = isWindows ? 'bun.exe' : 'bun';
|
||||
|
||||
// 尝试从环境变量中获取 BUN_PATH
|
||||
if (process.env.BUN_PATH) {
|
||||
return process.env.BUN_PATH;
|
||||
}
|
||||
|
||||
// 在 Windows 上,尝试查找通过 npm/nvm 安装的 bun
|
||||
if (isWindows) {
|
||||
try {
|
||||
// 获取全局 node_modules 路径
|
||||
const globalNodeModules = execSync('npm root -g', { encoding: 'utf-8' }).trim();
|
||||
const bunExePath = path.join(globalNodeModules, 'bun', 'bin', 'bun.exe');
|
||||
|
||||
if (fs.existsSync(bunExePath)) {
|
||||
return bunExePath;
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略错误,继续尝试其他路径
|
||||
}
|
||||
|
||||
// 尝试从 which/where 命令获取 bun 路径
|
||||
try {
|
||||
const bunPath = execSync('where bun', { encoding: 'utf-8' }).trim().split('\n')[0];
|
||||
if (bunPath && bunPath.endsWith('.exe')) {
|
||||
return bunPath;
|
||||
}
|
||||
// 如果 where bun 返回的是 shell 脚本,查找对应的 .exe
|
||||
if (bunPath) {
|
||||
const bunDir = path.dirname(bunPath);
|
||||
const bunExePath = path.join(bunDir, 'node_modules', 'bun', 'bin', 'bun.exe');
|
||||
if (fs.existsSync(bunExePath)) {
|
||||
return bunExePath;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略错误
|
||||
}
|
||||
} else {
|
||||
// Unix-like 系统
|
||||
try {
|
||||
const bunPath = execSync('which bun', { encoding: 'utf-8' }).trim();
|
||||
if (bunPath && fs.existsSync(bunPath)) {
|
||||
return bunPath;
|
||||
}
|
||||
} catch (error) {
|
||||
// 忽略错误
|
||||
}
|
||||
}
|
||||
|
||||
// 常见的 bun 安装路径
|
||||
const commonPaths = [
|
||||
'/usr/local/bin/bun',
|
||||
'/usr/bin/bun',
|
||||
'C:\\Program Files\\Bun\\bun.exe',
|
||||
'C:\\Bun\\bun.exe',
|
||||
];
|
||||
|
||||
for (const p of commonPaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果找不到,返回默认的 bun 名称,假设在 PATH 中
|
||||
return bunExecutableName;
|
||||
}
|
||||
Reference in New Issue
Block a user