diff --git a/index.js b/index.js index e2b5eb6..84723e8 100644 --- a/index.js +++ b/index.js @@ -9,29 +9,43 @@ import crypto from 'crypto'; import { readFileSync } from 'fs'; import { join, dirname } from 'path'; import { fileURLToPath } from 'url'; +import { homedir } from 'os'; -// Load environment variables from .env file +// Load environment variables from ~/.env file (standardized location) +const envPath = join(homedir(), '.env'); + +// Also try relative path as fallback for backwards compatibility const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); -const envPath = join(__dirname, '../.env'); +const envPathFallback = join(__dirname, '../.env'); -try { - const envFile = readFileSync(envPath, 'utf8'); - const envVars = envFile.split('\n').filter(line => line.includes('=') && !line.trim().startsWith('#')); - for (const line of envVars) { - const [key, ...values] = line.split('='); - // Validate key is a valid environment variable name (alphanumeric and underscore only) - if (key && values.length > 0 && /^[A-Z_][A-Z0-9_]*$/.test(key.trim())) { - // Remove surrounding quotes if present and trim - let value = values.join('=').trim(); - if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { - value = value.slice(1, -1); +function loadEnvFile(filePath) { + try { + const envFile = readFileSync(filePath, 'utf8'); + const envVars = envFile.split('\n').filter(line => line.includes('=') && !line.trim().startsWith('#')); + for (const line of envVars) { + const [key, ...values] = line.split('='); + // Validate key is a valid environment variable name (alphanumeric and underscore only) + if (key && values.length > 0 && /^[A-Z_][A-Z0-9_]*$/.test(key.trim())) { + // Remove surrounding quotes if present and trim + let value = values.join('=').trim(); + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { + value = value.slice(1, -1); + } + process.env[key.trim()] = value; } - process.env[key.trim()] = value; } + return true; + } catch (error) { + return false; + } +} + +// Try ~/.env first, then fallback to relative path +if (!loadEnvFile(envPath)) { + if (!loadEnvFile(envPathFallback)) { + console.error('Warning: Could not load .env file from ~/.env or ../.env'); } -} catch (error) { - console.error('Warning: Could not load .env file:', error.message); } class ProxmoxServer {