Skip to content

Commit

Permalink
refactor: streamline Node.js path configuration in task runner
Browse files Browse the repository at this point in the history
- 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.
  • Loading branch information
Marvin Zhang committed Jan 3, 2025
1 parent a585ab1 commit ff5cd32
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 27 deletions.
33 changes: 6 additions & 27 deletions core/task/handler/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 8 additions & 0 deletions core/utils/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const (
MetadataConfigDirName = ".crawlab"
MetadataConfigName = "config.json"
PyenvRoot = "/root/.pyenv"
DefaultNodeModulesPath = "/usr/lib/node_modules"
)

func IsDev() bool {
Expand Down Expand Up @@ -247,3 +248,10 @@ func GetInstallRoot() string {
}
return DefaultInstallRoot
}

func GetNodeModulesPath() string {
if res := viper.GetString("install.node.path"); res != "" {
return res
}
return DefaultNodeModulesPath
}

0 comments on commit ff5cd32

Please sign in to comment.