Check for current Node Version - node.js

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.

Look at process.version property.

process.version.match(/^v(\d+\.\d+)/)[1]
if process.version is 'v0.11.5', then get 0.11 .

Actually it would be better to use process.versions object which provides a lot of versions for the different node components.
Example:
{
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'
}

Use semver to compare process.version:
const semver = require('semver');
if (semver.gte(process.version, '0.12.18')) {
...
}

If you need to only check for the major version, you can use this quick-and-dirty snippet:
const NODE_MAJOR_VERSION = process.versions.node.split('.')[0];
if (NODE_MAJOR_VERSION < 12) {
throw new Error('Requires Node 12 (or higher)');
}
Notes:
process.versions.node is easier to work with than process.version, as you do not have to worry about whether the version starts with a leading v.
If you still need to distinguish between ancient versions (e.g., 0.10 and 0.12), this will not work, as they will all be considered version "0".

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=$(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."
}

If you access node js running environments, there are 2 main entries: (one simeple, one detail)
process.version will give you:
'v10.16.0'
process.versions will give you:
{ 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' }

I had the similar issue with my codebase. I wanted to know the current NodeJs version I am going to use to run my server at runtime. For that, I wrote a code which can be run before starting the Server using npm run start script.
Found below code helpful from this question.
'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}.`);
}
My package.json looks like this:
{
"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"
}
}
Do run npm install command before you run npm run start command to run your project.

also instead of writing this whole as suggested by #alsotang
Number(process.version.match(/^v(\d+\.\d+)/)[1])
(not saying this is a bad solution).
you can simply write
parseFloat(process.versions.node); it is versions (plural) not version
to get same or (similar) result and is easy to read

How about this, for major, minor
const [NODE_MAJOR_VERSION, NODE_MINOR_VERSION] = process.versions.node.split('.')

Related

Cannot find module 'node:url' when executing typescript from webstorm

I have written this small typescript hello world example
import axios from 'axios';
import { wrapper } from 'axios-cookiejar-support';
import { CookieJar } from 'tough-cookie';
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
client.get('https://example.com');
when I run this from webstorm i get the following error
/usr/bin/node /usr/local/lib/node_modules/ts-node/dist/bin.js /home/nayana/WebstormProjects/hello-world/hello.ts
Error: Cannot find module 'node:url'
anyone have idea on how to resolve this?
I already tried npm install node:url and url
i have isolated the error to this line
const client = wrapper(axios.create({ jar }));
The issue maybe is related to the node version.
The axios-cookiejar-support requires a specific node version ("node": ">=14.18.0 <15.0.0 || >=16.0.0").
Check node --version and package-lock.json.
Sample:
"node_modules/axios-cookiejar-support": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/axios-cookiejar-support/-/axios-cookiejar-support-4.0.3.tgz",
"integrity": "sha512-fMQc0mPR1CikWZEwVC6Av+sD4cJuV2eo06HFA+DfhY54uRcO43ILGxaq7YAMTiM0V0SdJCV4NhE1bOsQYlfSkg==",
"dependencies": {
"http-cookie-agent": "^4.0.2"
},
"engines": {
"node": ">=14.18.0 <15.0.0 || >=16.0.0"
},
"peerDependencies": {
"axios": ">=0.20.0",
"tough-cookie": ">=4.0.0"
}
},
You might need to install a later version of node.js.
I was running 14.17.6 and after installing 16.17.0 with nvm then I was able to run the project.
If you have nvm installed you can install a specific version of node e.g.
nvm install 16.17.0
make sure the types array in your tsconfig.json file contains "node"
{
"compilerOptions": {
"types": [
// ... your other types
"node"
],
// ... your other settings
},
}
The only thing you need to do, if you didn't install typescript is to change in the vite.config.js file, the import line like this:
import { fileURLToPath, URL } from 'node:url'
To:
import { fileURLToPath, URL } from 'url'

TypeError: trying to use aws-elasticsearch-connector

I'm attempting to update a legacy elastic-search node app, using the the package aws-elasticsearch-connector
and for some reason I'm unable to get it to work at all, even the simplest provided example...
I installed the packages, exactly as shown...
> npm install --save aws-elasticsearch-connector #elastic/elasticsearch aws-sdk
This is the sample code...
const { Client } = require('#elastic/elasticsearch')
const AWS = require('aws-sdk')
const createAwsElasticsearchConnector = require('aws-elasticsearch-connector')
// (Optional) load profile credentials from file
AWS.config.update({
profile: 'myawsprofile'
})
const client = new Client({
...createAwsElasticsearchConnector(AWS.config),
node: 'https://my-elasticsearch-cluster.us-east-1.es.amazonaws.com'
})
When I attempt to run it with this...
> node .\index.js
I get this error...
class AmazonConnection extends Connection {
TypeError: Class extends value undefined is not a constructor or null
I have no idea how I'm supposed to fix this, since the error seems to be in the module itself, not my sample code.
Most of the examples of this error that I've seen, suggest that it's related to circular references, but that doesn't seem to be of any help to me.
I'm using node v16.14.0
This is my package.json...
{
"name": "test_es",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#elastic/elasticsearch": "^8.0.0",
"aws-elasticsearch-connector": "^9.0.3",
"aws-sdk": "^2.1087.0"
}
}
I'm probably doing something wrong, or the package author may be assuming some additional knowledge that I just don't have.
Any suggestions would be greatly appreciated.
It seems version 8 of #elastic/elasticsearch is not compatible with aws-elasticsearch-connector.
Changing to version 7.17.0 seems to resolve this particular error.

Nuxt installation error : Rule can only have one resource source (provided resource and test + include + exclude)

I successfully installed Vuejs and Nodejs but got a problem when installing Nuxtjs. This is what I get. I already asked some friends but it didn't work. Thanks for your help ! :)
Error : Rule can only have one resource source (provided resource and test + include + exclude)
Rule can only have one resource source (provided resource and test + include + exclude) in {
"use": [
{
"loader": "C:\\Users\\User\\Desktop\\JS\\my-first-project\\node_modules\\babel-loader\\lib\\index.js",
"options": {
"configFile": false,
"babelrc": false,
"cacheDirectory": true,
"envName": "server",
"presets": [
[
"C:\\Users\\User\\Desktop\\JS\\my-first-project\\node_modules\\#nuxt\\babel-preset-app\\src\\index.js",
{
"corejs": {
"version": 3
}
}
]
]
},
"ident": "clonedRuleSet-30[0].rules[0].use[0]"
}
]
}
"use": [
{
"loader": "C:\\Users\\User\\Desktop\\JS\\my-first-project\\node_modules\\babel-loader\\lib\\index.js",
"options": {
"configFile": false,
"babelrc": false,
"cacheDirectory": true,
"envName": "server",
"presets": [
[
"C:\\Users\\User\\Desktop\\JS\\my-first-project\\node_modules\\#nuxt\\babel-preset-app\\src\\index.js",
{
"corejs": {
"version": 3
}
}
]
]
},
"ident": "clonedRuleSet-30[0].rules[0].use[0]"
}
]
}
at checkResourceSource (node_modules\#nuxt\webpack\node_modules\webpack\lib\RuleSet.js:167:11)
at Function.normalizeRule (node_modules\#nuxt\webpack\node_modules\webpack\lib\RuleSet.js:198:4)
at node_modules\#nuxt\webpack\node_modules\webpack\lib\RuleSet.js:110:20
at Array.map (<anonymous>)
at Function.normalizeRules (node_modules\#nuxt\webpack\node_modules\webpack\lib\RuleSet.js:109:17)
at new RuleSet (node_modules\#nuxt\webpack\node_modules\webpack\lib\RuleSet.js:104:24)
at new NormalModuleFactory (node_modules\#nuxt\webpack\node_modules\webpack\lib\NormalModuleFactory.js:115:18)
at Compiler.createNormalModuleFactory (node_modules\#nuxt\webpack\node_modules\webpack\lib\Compiler.js:636:31)
at Compiler.newCompilationParams (node_modules\#nuxt\webpack\node_modules\webpack\lib\Compiler.js:653:30)
at Compiler.compile (node_modules\#nuxt\webpack\node_modules\webpack\lib\Compiler.js:661:23)
at node_modules\#nuxt\webpack\node_modules\webpack\lib\Watching.js:77:18
at AsyncSeriesHook.eval [as callAsync] (eval at create (node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:22:1)
at AsyncSeriesHook.lazyCompileHook (node_modules\tapable\lib\Hook.js:154:20)
at Watching._go (node_modules\#nuxt\webpack\node_modules\webpack\lib\Watching.js:41:32)
at node_modules\#nuxt\webpack\node_modules\webpack\lib\Watching.js:33:9
at Compiler.readRecords (node_modules\#nuxt\webpack\node_modules\webpack\lib\Compiler.js:529:11)
npm i -D webpack#^4.46.0 try this, it worked for me.
I've had the same issue today, it seems to be related to an npm dependencies resolution issue.
I have opened an issue in nuxt.js repository
In my project, the issue was present, cause of #nuxtjs/eslint-module, you can remove it and regen dependencies :
npm uninstall #nuxtjs/eslint-module
rm -rf node_modules package-lock.json
npm install
You will not longer have eslint feedbacks in your build command, but you can still use npm run lint, and you will be able to use nuxt until the issue will be fixed.
I ran into this same error while trying to upgrade one of my old NuxtJS projects (using sass) built on node version 12 to version 16.
To fix this, i also installed #nuxtjs/style-resources that matches my versions of sass-loader and node-sass.
To confirm, uninstall the ones you already have, and run
npm install --save-dev node-sass sass-loader#10 fibers #nuxtjs/style-resources
see this article for more
This happened to me when I installed the most recent version of copy-webpack-plugin in Nuxt v2 project. Apparently it doesn't use webpack5 so I had to downgrade copy-webpack-plugin to last compatible version e.g. copy-webpack-plugin#4.6.0

bundle.js bundle.js:1 Uncaught Error: Cannot find module '/node_modules\mongodb-core\lib\topologies/../../package.json'

I am getting the below error:
bundle.js:1 Uncaught Error: Cannot find module '/node_modules\mongodb-ore\lib\topologies/../../package.json'
Here is my version detial:
OS: Windows10
MongoDB: 2.2.16
MongoDB-core: 2.1.2
Node: 6.9.2
I have used npm install bson-ext and changed \node_modules\mongodb-core\node_modules\bson-ext\ext\index.js to
try {
// Load the precompiled win32 binary
if(process.platform == "win32" && process.arch == "x64") {
bson = require('bson');
} else if(process.platform == "win32" && process.arch == "ia32") {
bson = require('bson');
} else {
bson = require('bson');
}
} catch(err) {
console.log(err)
// Attempt to load the release bson version
try {
bson = require('bindings')('bson.node');
} catch (err) {
throw new Error("js-bson: Failed to load c++ bson extension, using pure JS version");
}
}
while the original is:
bson = require('./win32/x64/bson');
because when I try browserify range.js > bundle.js, it cannot find bson-ext module in mongoDB-core.
I am not sure whether this kind of operation may cause the above error.
Here is my package.json file :
"dependencies": {
"browserify": "^13.1.1",
"bson": "^1.0.1",
"d3": "^4.4.0",
"express": "^4.14.0",
"hbs": "^4.0.1",
"jsdom": "^9.9.1",
"mongodb": "^2.2.16",
"mongodb-core": "^2.1.2"
}
I haven't been able to confirm this yet, but I think the problem is that MongoDB's JavaScript (Node.js) driver is not intended for use in a browser, for security reasons. Not clear if the problem in the OP is due to Browserify incorrectly resolving relative paths or something else, but regardless the preferred technique is to proxy requests to your MongoDB instance via a Node server.
Mongo lists off-the-shelf solutions for this here:
https://docs.mongodb.com/ecosystem/tools/http-interfaces/
Note also the --rest option, which allows an application to read directly from the DB via a URL schema:
https://docs.mongodb.com/ecosystem/tools/http-interfaces/#simple-rest-api
As the docs mention, this is not good practice for security concerns, but may help with prototyping.

Meteor.js Browserify error using an npm module with meteorhacks:npm and browserify

Browserify file (client/app.browserify.js):
react-typist = require('react-typist');
packages.json:
{
"redis": "0.8.2",
"github": "0.1.8",
"react-typist": "0.3.0"
}
I am receiving this error:
Browserify error:
While processing files with cosmos:browserify (for target web.browser):
client/app.browserify.js: Parsing file /Users/*********/www/app-react/packages/npm-container/.npm/package/_stream_0.js: Assigning to rvalue (1:0)
Browserify options:
> {
> "basedir": "/Users/***********/www/app-react/packages/npm-container/.npm/package",
> "debug": true,
> "transforms": {}
}
react-typist = require('react-typist');
is not valid when assigning variable. It should be
Typist = require('react-typist');

Resources