it-source

현재 노드 버전 확인

criticalcode 2023. 7. 25. 21:06
반응형

현재 노드 버전 확인

작성 중인 라이브러리에서 실행 중인 현재 노드 버전에 프로그래밍 방식으로 액세스해야 합니다.문서에서 이걸 찾을 수 없는 것 같습니다.

과정을 살펴봅니다.버전 속성.

process.version.match(/^v(\d+\.\d+)/)[1]

한다면process.version'v0.11.5'입니다. 그런 다음0.11.

사실은 그것을 사용하는 것이 더 나을 것입니다.process.versions다양한 노드 구성 요소에 대한 많은 버전을 제공하는 개체입니다.예:

{
  http_parser: '2.5.2',
  node: '4.4.3',
  v8: '4.5.103.35',
  uv: '1.8.0',
  zlib: '1.2.8',
  ares: '1.10.1-DEV',
  icu: '56.1',
  modules: '46',
  openssl: '1.0.2g'
}

semver를 사용하여 비교process.version:

const semver = require('semver');

if (semver.gte(process.version, '0.12.18')) {
  ...
}

주 버전만 확인해야 하는 경우 다음과 같은 빠르고 더러운 스니펫을 사용할 수 있습니다.

const NODE_MAJOR_VERSION = process.versions.node.split('.')[0];
if (NODE_MAJOR_VERSION < 12) {
  throw new Error('Requires Node 12 (or higher)');
}

주의:

  • process.versions.node보다 작업하기 쉽습니다.process.version버전이 선두로 시작하는지 여부에 대해 걱정할 필요가 없기 때문에v.
  • 여전히 고대 버전(예: 0.10 및 0.12)을 구별해야 하는 경우에는 모두 버전으로 간주되므로 이 작업이 수행되지 않습니다."0".

또한 버전을 비교하기 위해 탕의 답변을 조금 수정했습니다.

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

어설션을 수행하려면 다음과 같이 수행합니다.

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

bash에서 사용할 한 줄로 단축할 수 있습니다.

NODE_VERSION=$(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

또는 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."
}

실행 중인 노드 js 환경에 액세스하는 경우 두 가지 주요 항목이 있습니다. (단순한 항목, 세부 정보 하나)

  • process.version다음을 제공합니다.

'v10.16.0'

  • process.versions다음을 제공합니다.
{ http_parser: '2.8.0',
  node: '10.16.0',
  v8: '6.8.275.32-node.52',
  uv: '1.28.0',
  zlib: '1.2.11',
  brotli: '1.0.7',
  ares: '1.15.0',
  modules: '64',
  nghttp2: '1.34.0',
  napi: '4',
  openssl: '1.1.1b',
  icu: '64.2',
  unicode: '12.1',
  cldr: '35.1',
  tz: '2019a' }

제 코드베이스에도 비슷한 문제가 있었습니다.런타임에 서버를 실행하는 데 사용할 현재 NodeJs 버전을 알고 싶습니다.이를 위해 서버를 시작하기 전에 실행할 수 있는 코드를 작성했습니다.npm run start대본.아래 코드는 이 질문에서 도움이 됩니다.

'use strict';
const semver = require('semver');
const engines = require('./package').engines;
const nodeVersion = engines.node;

// Compare installed NodeJs version with required NodeJs version.
if (!semver.satisfies(process.version, nodeVersion)) {
  console.log(`NodeJS Version Check: Required node version ${nodeVersion} NOT SATISFIED with current version ${process.version}.`);
  process.exit(1);
} else {
  console.log(`NodeJS Version Check: Required node version ${nodeVersion} SATISFIED with current version ${process.version}.`);
}

내 소포.json은 다음과 같이 보입니다.

{
  "name": "echo-server",
  "version": "1.0.0",
  "engines": {
    "node": "8.5.0",
    "npm": "5.3.0"
  },
  "description": "",
  "main": "index.js",
  "scripts": {
    "check-version" : "node checkVersion.js",
    "start-server" : "node app.js"
    "start" : "npm run check-version && npm run start-server",
    "test": "npm run check-version && echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bluebird": "^3.5.1",
    "express": "^4.16.3",
    "good-guy-http": "^1.10.3",
    "semver": "^5.5.0"
  }
}

실행npm install실행 전 명령npm run start프로젝트를 실행하는 명령입니다.

또한 @alsotang이 제안한 것처럼 이 전체를 쓰는 대신.

Number(process.version.match(/^v(\d+\.\d+)/)[1])

(이것이 나쁜 해결책이라고 말하지 않음).

당신은 간단하게 쓸 수 있습니다.

parseFloat(process.versions.node); 버전이 아닌 버전(하드웨어)입니다.

동일하거나 (비슷한) 결과를 얻고 읽기 쉽습니다.

참고: 댓글에서 지적한 것처럼 마이너 버전이 9보다 크지 않을 것이라는 것을 알고 있는 경우에만.

소령님, 소령님, 이것은 어떻습니까?

const [NODE_MAJOR_VERSION, NODE_MINOR_VERSION] = process.versions.node.split('.')

언급URL : https://stackoverflow.com/questions/6656324/check-for-current-node-version

반응형