回答:
process.versionプロパティを確認してください。
process.version.match(/^v(\d+\.\d+)/)[1]
process.versionが 'v0.11.5'の場合、を取得し0.11ます。
node-semverです、より良い解決策です
semverを使用して比較しprocess.versionます。
const semver = require('semver');
if (semver.gte(process.version, '0.12.18')) {
...
}
実際には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'
}
メジャーバージョンのみを確認する必要がある場合は、次のクイックアンドダーティースニペットを使用できます。
const NODE_MAJOR_VERSION = process.versions.node.split('.')[0];
if (NODE_MAJOR_VERSION < 12) {
throw new Error('Requires Node 12 (or higher)');
}
ノート:
process.versions.nodeprocess.versionバージョンが先頭で始まるかどうかを心配する必要がないので、を使用する方が簡単vです。"0"。私のコードベースにも同様の問題がありました。実行時にサーバーを実行するために使用する現在のNodeJのバージョンを知りたいのですが。そのために、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}.`);
}
私のpackage.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あなたのプロジェクトを実行するコマンドを。
ノードjs実行環境にアクセスする場合、2つのメインエントリがあります:(1つのサンプル、1つの詳細)
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' }