From ff5cd32de48418cac5959a3654de9c5054d3b905 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Fri, 3 Jan 2025 16:49:24 +0800 Subject: [PATCH] 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. --- core/task/handler/runner.go | 33 ++++++--------------------------- core/utils/config.go | 8 ++++++++ 2 files changed, 14 insertions(+), 27 deletions(-) diff --git a/core/task/handler/runner.go b/core/task/handler/runner.go index d0493742..6bfadba4 100644 --- a/core/task/handler/runner.go +++ b/core/task/handler/runner.go @@ -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: diff --git a/core/utils/config.go b/core/utils/config.go index 3387ff65..f798c2ff 100644 --- a/core/utils/config.go +++ b/core/utils/config.go @@ -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 +}