refactor: streamline Node.js path configuration in task runner

- Removed redundant home directory retrieval and nvm checks in the configureNodePath method.
- Introduced a new utility function GetNodeModulesPath to centralize the logic for determining the global node_modules path.
- Updated environment variable setup to use the new utility function, improving clarity and maintainability of the code.
This commit is contained in:
Marvin Zhang
2025-01-03 16:49:24 +08:00
parent a585ab16f7
commit ff5cd32de4
2 changed files with 13 additions and 26 deletions

View File

@@ -342,36 +342,15 @@ func (r *Runner) startHealthCheck() {
// configureNodePath sets up the Node.js environment paths, handling both nvm and default installations
func (r *Runner) configureNodePath() {
// Get user's home directory
home, err := os.UserHomeDir()
if err != nil {
r.Errorf("error getting user home directory: %v", err)
home = "/root" // fallback to root if it can't get home dir
}
// Configure nvm-based Node.js paths
envPath := os.Getenv("PATH")
nvmPath := filepath.Join(home, ".nvm/versions/node")
// Check if nvm is being used
if utils.Exists(nvmPath) {
// Get the current node version from NVM
currentVersion := os.Getenv("NVM_BIN")
if currentVersion != "" {
nodePath := filepath.Dir(currentVersion) + "/lib/node_modules"
if !strings.Contains(envPath, nodePath) {
_ = os.Setenv("PATH", nodePath+":"+envPath)
}
_ = os.Setenv("NODE_PATH", nodePath)
}
} else {
// Fallback to default global node_modules path
nodePath := "/usr/lib/node_modules"
if !strings.Contains(envPath, nodePath) {
_ = os.Setenv("PATH", nodePath+":"+envPath)
}
_ = os.Setenv("NODE_PATH", nodePath)
// Configure global node_modules path
nodePath := utils.GetNodeModulesPath()
if !strings.Contains(envPath, nodePath) {
_ = os.Setenv("PATH", nodePath+":"+envPath)
}
_ = os.Setenv("NODE_PATH", nodePath)
}
// configureEnv sets up the environment variables for the task process, including:

View File

@@ -31,6 +31,7 @@ const (
MetadataConfigDirName = ".crawlab"
MetadataConfigName = "config.json"
PyenvRoot = "/root/.pyenv"
DefaultNodeModulesPath = "/usr/lib/node_modules"
)
func IsDev() bool {
@@ -247,3 +248,10 @@ func GetInstallRoot() string {
}
return DefaultInstallRoot
}
func GetNodeModulesPath() string {
if res := viper.GetString("install.node.path"); res != "" {
return res
}
return DefaultNodeModulesPath
}