Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature]: NVM automatic version change based on .nvmrc file Using JS Script Available to use #1047

Closed
proCoderSid opened this issue Oct 9, 2023 · 4 comments

Comments

@proCoderSid
Copy link

Description of the new feature / enhancement

I have created this script and it is for user convince to go to check script

Automatic Node.js Version Checker Script

This JavaScript script automates the process of checking and managing Node.js versions based on specific conditions:

  1. Check Current Node.js Version:

    • The script begins by checking the currently installed Node.js version on your system.
  2. Comparison with Required Version from .nvmrc File:

    • If the currently installed Node.js version matches the required version, the script logs a success message and terminates.
  3. Using Node Version from .nvmrc File:

    • If the installed Node.js version doesn't match the required version, the script looks for a Node.js version specified in a .nvmrc file in your project directory.
    • If an .nvmrc file is found and contains a valid Node.js version, the script switches to and uses that version.
  4. Installing Missing Node.js Version:

    • If there's no .nvmrc file or the specified version is not installed, the script prompts the user with a confirmation message.
    • If the user chooses to install the required version, the script proceeds to install it using a nvm install versioncommand
    • After installation, the script switche and uses the newly installed version.
  5. Terminating the Script:

    • If the user chooses not to install the required version, the script gracefully terminates.

This script provides an automated and user-friendly way to ensure that your Node.js environment is set to the required version for your project.

Usage

the script is available at https://github.com/proCoderSid/nvm-chk.git

You can use this file in package.json file as follow or as you feel comfortable to use

{
    "scripts": {
        "prestart": "node nvm-chk.js",
        "start": "Your start command"
    }
}

I have tested this script in node v4.9.11 to latest,
It works fine and if not working in any specific version then let me know I will update the script

Prerequisites as follow

  • Must have nvm installed on your machine
  • Current in use version of node need to be grater then v4.9.11

Scenario when this would be used?

  • Can be use before starting your local environment
  • Can be use to switch version automatically

Supporting information

const childProcess = require("child_process");
const fs = require("fs");
const readline = require("readline");
const execSync = childProcess.execSync;

// Read .nvmrc file
const nvmrcPath = ".nvmrc"; // Replace with your .nvmrc file path

const main = () => {
  try {
    // Read the content of the .nvmrc file
    const nvmrcVersion = fs.readFileSync(nvmrcPath, "utf-8").trim();

    // Get the current version of Node.js installed on the system
    const currentVersion = execSync("nvm current", { encoding: "utf-8" }).trim();

    if (currentVersion !== nvmrcVersion) {
      console.log("Current Node.js version:", currentVersion);
      console.log("Trying to use .nvmrc file version:", nvmrcVersion);

      try {
        nvmUseVersion(nvmrcVersion);
      } catch (err) {
        console.error("Error using Node.js version from .nvmrc:", err);
        console.log(`Please manually run 'nvm use ${nvmrcVersion}' to switch to the desired version.`);
      }
    } else {
      console.log("Node.js versions match:", currentVersion);
    }
  } catch (err) {
    console.error("Error reading .nvmrc file:", err);
  }
};

const requestToInstallNewVersion = (nvmrcVersion) => {
  // Prompt the user for installation confirmation
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  rl.question("Do you want to install this version? (y/n): ", (answer) => {
    rl.close();
    if (answer.toLowerCase() === "y") {
      try {
        // Install the desired version using `nvm install`
        const installOutput = execSync(`nvm install ${nvmrcVersion}`, { encoding: "utf-8" }).trim();
        console.log(installOutput);
        nvmUseVersion(nvmrcVersion);
      } catch (err) {
        console.error("Error installing Node.js:", err);
      }
    }
  });
};

const checkVersionAfterUpdate = (nvmrcVersion) => {
  const updatedVersion = execSync("nvm current", { encoding: "utf-8" }).trim();
  if (updatedVersion !== nvmrcVersion) {
    console.log("Node.js version did not switch successfully. Please run the nvm use command manually.");
  } else {
    console.log("Updated Node.js version:", updatedVersion);
  }
};

const nvmUseVersion = (nvmrcVersion) => {
  // Attempt to switch to the desired Node.js version using `nvm use`
  const useOutput = execSync(`nvm use ${nvmrcVersion}`, { encoding: "utf-8" }).trim();

  if (useOutput.includes("is not installed.")) {
    // If the desired version is not installed, check available versions
    const versions = execSync("nvm ls", { encoding: "utf-8" });

    if (!versions.includes(nvmrcVersion)) {
      console.log(`Node.js version ${nvmrcVersion} is not installed.`);

      requestToInstallNewVersion(nvmrcVersion);
    }
  } else {
    checkVersionAfterUpdate(nvmrcVersion);
  }
};

main();
@proCoderSid proCoderSid changed the title [Feature]: NVM automatic version change based on .nvmrc file [Feature]: NVM automatic version change based on .nvmrc file Using JS Script Available to use Oct 9, 2023
@coreybutler
Copy link
Owner

Since this is a feature I'm not implementing in NVM4W, I'm closing this. However; I'm going to link to this from the wiki for people who want this functionality.

@coreybutler
Copy link
Owner

This now linked in the common issues wiki page.

@erikmusd
Copy link

Just for those trying to use this script, it doesn't work with 1.1.12. However, it does work with 1.1.11. See #1068

@erikmusd
Copy link

In addition I had to tweak two lines because when comparing values it would fail since some versions have leading "v" before version i.e. 'v18.0.0' === '18.0.0' would fail, though technically they are the same version.

currentVersion = currentVersion.startsWith( 'v' ) ? currentVersion.slice( 1 ) : currentVersion;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants