Check for current Node Version

后端 未结 9 1862
温柔的废话
温柔的废话 2021-01-31 06:48

I need to programmatically access the current node version running in a library I am writing. Can\'t seem to find this in the docs.

9条回答
  •  伪装坚强ぢ
    2021-01-31 07:26

    I refined alsotang's answer a bit to compare versions:

    const m = process.version.match(/(\d+)\.(\d+)\.(\d+)/);
    const [major, minor, patch] = m.slice(1).map(_ => parseInt(_));
    

    To perform an assertion, do it like this:

    if (major >= 13 || (major >= 12 && minor >= 12)) {
        console.log("NodeJS is at least v12.12.0. It is safe to use fs.opendir!");
    }
    

    This can be shortened to a one-liner to use in bash:

    NODE_VERSION_CHECK=$(node -e "const v = process.version.match(/(\\d+)\.(\\d+)\.(\\d+)/).slice(1).map(_ => parseInt(_)); console.log(v[0] >= 13 || (v[0] >= 12 && v[1] >= 12))")
    if $NODE_VERSION -eq "true" ;
    then
        echo "NodeJS is at least v12.12.0."
    fi
    

    or PowerShell:

    $nodeVersion = $(node -e "const v = process.version.match(/(\d+)\.(\d+)\.(\d+)/).slice(1).map(_ => parseInt(_)); console.log(v[0] >= 13 || (v[0] >= 12 && v[1] >= 12))")
    if ($nodeVersion -eq "true") {
        Write-Host "NodeJS is at least v12.12.0."
    }
    

提交回复
热议问题