Node: check latest version of package programmatically - javascript

I'd like my node package (published on npm) to alert the user when a new version is available. How can i check programmatically for the latest version of a published package and compare it to the current one?
Thanks

You can combine the npmview (for getting remote version) and semver (for comparing versions) packages to do this:
const npmview = require('npmview');
const semver = require('semver');
// get local package name and version from package.json (or wherever)
const pkgName = require('./package.json').name;
const pkgVersion = require('./package.json').version;
// get latest version on npm
npmview(pkgName, function(err, version, moduleInfo) {
// compare to local version
if(semver.gt(version, pkgVersion)) {
// remote version on npm is newer than current version
}
});

Related

NodeJS, crypto.randomUUID is not a function

I'm very new to JS, I want to generate an UUID. Here's what I tried, step by step:
mkdir test
cd test
touch file1.js
Inside file1.js:
let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
var uuid = crypto.randomUUID();
console.log(uuid);
And you see the error. What is wrong? I can't find answer anywhere. Node JS version:
node -v shows v12.22.9
here you can use randomBytes() method for get unique id
const crypto = require('crypto');
console.log(crypto.randomBytes(20).toString('hex'));
you can also use uuidv4 instead of crypto
const { uuid } = require('uuidv4');
console.log(uuid());
The error is that the crypto.randomUUID function was added for Node versions > v14.17.0.
That is according to the official docs: https://nodejs.org/api/crypto.html#cryptorandomuuidoptions
So probably your best choice, if you do not want to use newer Node versions, would be to use https://www.npmjs.com/package/uuid
I upgraded NodeJS to newer version, and it worked!
I had some problems, so I tried to remove NodeJS (I had the same problem like this guy: https://github.com/nodesource/distributions/issues/1157).
And installed LTS version: https://askubuntu.com/questions/1265813/how-to-update-node-js-to-the-long-term-support-version-on-ubuntu-20-04.
Now I have:
node -v
v16.16.0
and script works! Thank you :)

const utf8Encoder = new TextEncoder(); in Node js

I am trying to use mongodb so I install mongoose package
but the problem is when I am writing like this
const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose"); //getting error here
It showing me error like this
const utf8Encoder = new TextEncoder();
^
ReferenceError: TextEncoder is not defined
If I am commenting mongoose line I don't get any error but I need to use this even i checked my node version its 16.5.0
I tried looking an old post where same error occur but its not understandable to me any help ? old post link
enter link description here
how to fix this error
Open your encoding.js folder in node_modules>whatwg-url>dist
and write this code
"use strict";
var util= require('util');
const utf8Encoder = new util.TextEncoder();
const utf8Decoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
in place of
"use strict";
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
all you where missing is this small part by including utils
var util= require('util');
const utf8Encoder = new util.TextEncoder();
const utf8Decoder = new util.TextEncoder("utf-8", { ignoreBOM: true });
This worked for me at the top of my small script file.
"use strict";
const util = require('util');
global.TextEncoder = util.TextEncoder;
global.TextDecoder = util.TextDecoder;
It's a compatibility issue with node.js version, upgrade your node.js version and then reinstall node packages.
Upgrade your version with: v16.14.2
It's not recommended to modify files inside the node_modules folder
You can use NVM to manage multiple node.js versions, here are the installation guide: https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-20-04
Open your encoding.js folder in node_modules
Open the node_modules
Locate the whawg-url folder and open.
Search for dist folder - there, you'd find the encoding.js folder
Open via VS Code or any IDE of your choice.
Replace these line of code
"use strict";
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
With this --
"use strict";
var util= require('util');
const utf8Encoder = new util.TextEncoder();
const utf8Decoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
Then you are good to go.
This seems to be an issue with older node versions. You need to use the latest node. If you are using nvm type
nvm use node
Note: to download latest node with nvm use this command
nvm install --lts
This is because your using an old version of node, if you install node using apt install node, you get an old version. So you need to upgrade to a recent version of node.
You just need a compatible node version of libraries in package.json. I encountered the same error the mistake I made is that I used nvm and I ran npm install with node v12.x.x for some reason nvm did not set the current version it set v10.x.x when I returned to the project folder. so here what I resolved the error:
$ rm -rf node_modules
# use another way to switch to the correct version if not using nvm
$ nvm use v12.x.x # Switch node version to v12.x.x
$ npm install
# then restart the server
if you use nvm and you want to set the project node version automatically when entering the project folder, just follow this instruction.

Test two different npm package versions at the same time

When I create an npm package, sometimes it would face the need to backward old dependency package version.
If the new version has new api, I may write the code in this pattern:
import pkg from 'some-pkg';
const isNewVersion = pkg.newVersionApi !== 'undefined';
if (isNewversion) {
pkg.newVersionApi();
} else {
pkg.oldVersionApi(); // backward compatible api
}
And with this pattern, when I want to write the test, I only can test the installed version code. The other version's code can't be tested.
For real example, in React v15 and v16, React v16 has new API Portal. Before Portal release, v15 has unstable_renderSubtreeIntoContainer api to realize similar feature.
So the code for React would be like:
import ReactDOM from 'react-dom';
const isV16 = ReactDOM.createPortal !== 'undefined';
if (isV16) {
ReactDOM.createPortal(...);
} else {
ReactDOM.unstable_renderSubtreeIntoContainer(...);
}
So I want to ask is there any method to test with different dependency version?
Currently, one method I think of is to install the other version again and test it. But it only can do on local. It can't work on ci and it can't count in coverage together.
I think that is not only for react test. It may face on node.js test. Any suggestion can be discussed.
Updated
This question maybe is related to install two versions dependency in npm. But I know currently installing two versions dependency is not workable.
Here is a might be solution, not sure it will work as you expect. But, you will have a direction to move forward.
package.json
{
"name": "express-demo",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.3",
"express": "~4.15.2",
"jade": "~1.11.0",
"morgan": "~1.8.1",
"serve-favicon": "~2.4.2",
"webpack": "^3.8.1",
"webpack-dev-middleware": "^1.12.0",
"webpack-hot-middleware": "^2.20.0"
},
"customDependecies": {
"body-parser": [
"",
"1.18.1",
"1.18.0"
]
}
}
Note in above package.json file, I have added a new key customDependecies which I will use for installing multiple dependencies. Here I am using body-parser package for demo. Next you need file, that can read this key and install the deps.
install-deps.js
const {spawnSync} = require('child_process');
const fs = require('fs');
const customDependencies = require('./package.json').customDependecies;
spawnSync('mkdir', ['./node_modules/.tmp']);
for (var dependency in customDependencies) {
customDependencies[dependency].forEach((version) => {
console.log(`Installing ${dependency}#${version}`);
if (version) {
spawnSync('npm', ['install', `${dependency}#${version}`]);
spawnSync('mv', [`./node_modules/${dependency}`, `./node_modules/.tmp/${dependency}#${version}`]);
} else {
spawnSync('npm', ['install', `${dependency}`]);
spawnSync('mv', [`./node_modules/${dependency}`, `./node_modules/.tmp/${dependency}`]);
}
});
customDependencies[dependency].forEach((version) => {
console.log(`Moving ${dependency}#${version}`);
if (version) {
spawnSync('mv', [`./node_modules/.tmp/${dependency}#${version}`, `./node_modules/${dependency}#${version}`]);
} else {
spawnSync('mv', [`./node_modules/.tmp/${dependency}`, `./node_modules/${dependency}`]);
}
});
}
spawnSync('rm', ['-rf', './node_modules/.tmp']);
console.log(`Installing Deps finished.`);
Here, I am installing deps one by one in tmp folder and once installed, I am moving them to ./node_modules folder.
Once, everything is installed, you can check the versions like below
index.js
var bodyParser = require('body-parser/package.json');
var bodyParser1181 = require('body-parser#1.18.1/package.json');
var bodyParser1182 = require('body-parser#1.18.0/package.json');
console.log(bodyParser.version);
console.log(bodyParser1181.version);
console.log(bodyParser1182.version);
Hope, this will serve your purpose.
Create 3 separate projects (folders with package.json) and a shared folder:
A shared folder containing the test module (my-test). Export a function to run the test;
A client project importing my-test and dependency v1. Export a function that calls the test function in my-test.
A client project importing my-test and dependency v2. Export a function that calls the test function in my-test.
A master project that imports both client projects. Run each exported function.
You're going to have to run them separately. Create a separate project folder for each dependency version. Ex. React10, React11, React12. Each will have its own package.json, specified for the correct version. When you run the integration and/or versioned tests, you'll run your standard unit tests across each version, but it may also be advisable to add any version specific unit tests to that folder.
Creating a make file would make your life easier when running your full testing suite. If you do this you can easily integrate this into CI.
In addition to the other suggestions, you can try the approach described at Testing multiple versions of a module dependency.
Here's an example of using this approach to test against multiple webpack versions:
npm install --save-dev module-alias
npm install --save-dev webpack-v4#npm:webpack#4.46.0
npm install --save-dev webpack-v5#npm:webpack#5.45.1
The module-alias package handles the magic of switching between package versions while still supporting normal require('webpack') (or whatever your module is) calls.
The other installs will create two versions of your dependency, each with a distinct directory name within your local node_modules/.
Then, within your test code, you can set up the dependency alias via:
const path = require('path');
require('module-alias').addAlias(
'webpack',
path.resolve('node_modules', 'webpack-v4'),
);
// require('webpack') will now pull in webpack-v4
You'd do the same thing for 'webpack-v5' in a different test harness.
If any of your sub-dependencies have a hardcoded require('webpack') anywhere in their own code, this will ensure that they also pull in the correct webpack version.

Unable to print data using console.table

I am using console.table in my program, test.js to display data but with no luck.
require('console.table');
var values = [
['max', 20],
['joe', 30]
];
console.table(['name', 'age'], values);
And when I run this app I get nothing on the screen
$ node test.js
$
I have already installed console.table
$ npm install --save console.table
npm WARN mysqldb#1.0.0 No description
npm WARN mysqldb#1.0.0 No repository field.
+ console.table#0.8.0
updated 1 package in 0.687s
$ node test.js
$
I am using Ubuntu 16.04, kindly advice.
Have you install console.table package or not.
If you didn't install then first install using
npm install --save console.table
Try this
require('console.table')
var values = [
['max', 20],
['joe', 30]
];
console.table(values);
This is my output
I am trying your script as well and I am getting result
Well for upper version of node.js you need not to install console.table if still you install you have to use console.table like as follows.
delete console.table;
require('console.table');
or
require('console.table')({force: true})
This issue is not of console.table .
Actually console.table does not work on version node 7+
version node 6.11
the output is this
and in version node 8.0
the output is
I have used a frame work called columnify - npm install columnify
const columnify = require('columnify');
//Connect to datbase (mycompany) collection
db.collection('employee').find({}, {projection:{_id: 0}}).toArray((err, allRecords) => {
//Error checking
if (err) {
console.log('Error encontered!!!');
} else {
console.log(columnify(allRecords));
process.exit(0);
};
});

ReferenceError: TextEncoder is not defined

I'm writing a simple addon in Firefox - 24, on Linux.
I get the error:
ReferenceError: TextEncoder is not defined
when I do: var encoder = new TextEncoder();
the function I'm using is:
function write_text(filename, text) {
var encoder = new TextEncoder();
var data = encoder.encode(text);
Task.spawn(function() {
let pfh = OS.File.open("/tmp/foo", {append: true});
yield pfh.write(text);
yield pfh.flush();
yield pfh.close();
});
}
if you are having this error while running node server
locate this file node_modules/whatwg-url/dist/encoding.js or .../lib/encoding.js
add this line at top const { TextEncoder, TextDecoder } = require("util");
In nodejs you can solve with util:
var util= require('util');
var encoder = new util.TextEncoder('utf-8');
If you experienced this because of using Mongodb via npm install mongodb then the simplest way is just to upgrade your Node Version. Needs to be higher than version 12; I used version 16 and it clearly fixed my problem
This issue occurs in node 10 or lower version only. To resolve this issue upgrade node version to 12 or higher and then rm -rf node_modules && npm i
Or If you don't want to upgrade node version, then,
Locate this file
node_modules/whatwg-url/dist/encoding.js // If dist folder
node_modules/whatwg-url/lib/encoding.js // If lib folder
And add this line in encoding.js file
const { TextEncoder, TextDecoder } = require("./utils"); // if utils file
const { TextEncoder, TextDecoder } = require("./util"); // if util file
Ah, you're using the SDK, I gather when re-reading the actual error of your other question.
You need to import TextEncoder explicitly from some other module, as SDK modules lack the class.
You need to yield OS.File.open.
append: is only supported in Firefox 27+
.flush() is only supported in Firefox 27+ (and a bad idea anyway). Use .writeAtomic if you need that.
You write: true to write to a file.
Here is a full, working example I tested in Firefox 25 (main.js)
const {Cu} = require("chrome");
// It is important to load TextEncoder like this using Cu.import()
// You cannot load it by just |Cu.import("resource://gre/modules/osfile.jsm");|
const {TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});
const {Task} = Cu.import("resource://gre/modules/Task.jsm", {});
function write_text(filename, text) {
var encoder = new TextEncoder();
var data = encoder.encode(text);
filename = OS.Path.join(OS.Constants.Path.tmpDir, filename);
Task.spawn(function() {
let file = yield OS.File.open(filename, {write: true});
yield file.write(data);
yield file.close();
console.log("written to", filename);
}).then(null, function(e) console.error(e));
}
write_text("foo", "some text");
I was also getting this error so I solved it in this way,
in nodejs project go to the node_modules/whatwg-url/dist/encoding.js file in that add this line =>
const {TextDecoder, TextEncoder} = require("util");
And your problem is solved
A text encoder for Node.js can be found in the util module. You can access it like so:
const util = require('util');
const TextEncoder = new util.TextEncoder();
One of the roles of the TextEncoder is to convert a string of text into an array of bytes. You can achieve this like so:
const data = TextEncoder.encode(
JSON.stringify({ c: "Green" })
);
// Uint8Array [ 123, 34, 99, 34, 58, 34, 71, 114, 101, 101, 110, 34, 125 ]
The array returned is called a Uint8Array. It consists of integers in the range 0 to 255.
Note that TextEncoder only supports UTF-8 encoding.
For me upgrade Node.js version resolved this issue
Open your encoding.js folder in node_modules>whatwg-url>dist
And in place of:
"use strict";
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
Write this code:
"use strict";
var util= require('util');
const utf8Encoder = new util.TextEncoder();
const utf8Decoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
all you where missing is this small part by including utils.
The TextEncoder can be found in the sdk/io/buffer module:
let { TextEncoder, TextDecoder } = require('sdk/io/buffer')
If it's an error in node_modules/whatwg_url/dist/encoding.js folder then uninstall MongoDB by
npm uninstall mongodb
and reinstall it
npm install --save mongodb
I was also facing the same problem in my project but I fixed this issue by upgrading my node version from 10 to 12. May be this issue now a days can occurred due to lower version of node we are using in our project.
This looks like a node version error because I solved it by updating from 10 to 16 and after that, I installed dependencies and open a new terminal.
Update node to 14 or higher, I used Node Version Manager (NVM)
Delete node_modules directory, on linux:
rm -rf node_modules
Install dependencies with npm install
Close and open a new terminal
Run app with node or nodemon
Done!
This might help others.
I was getting the same error and I almost tried all the above solutions, but nothing works for me. Finally, I update the npm version and everything is fine.
When I installed the Next App the npm version was 6.14.4.
I update the version and all errors are fixed you don't need to change anything in the core files just update the version in my case recommended 8.11.0.
npm -v // Check the version
npm install -g npm#latest // Get the latest version
OR
npm install -g npm#8.11.0 // Get the Spacific version
Complete guid here
delete your 'node_modules' folder
rm -rf node_modules
then re-install dependencies
npm i
If you are using 'mongoose' greater than v6 you need at least Node.js v12
I was facing the same error, because of having to install old nodejs. This problem can be solved by installing the latest nodejs.
To update nodejs to nodejs to 14.x
sudo apt update
curl -sL https://deb.nodesource.com/setup_14.x | sudo bash -
sudo apt install -y nodejs
node -v
It's a node version problem.
Described by #yhojann-cl here
I have the same problem:
In /usr/bin/node I have 10.x, but 16.x is installed by nvm.
In my case, I had multiple node versions installed, and current project required a more recent node version. To fix the problem I did the following steps.
To check the current version of node running, in the terminal use the command
node --version
Output in the Terminal :
The following command will list the different node versions already installed in your system.
nvm ls
Output in the Terminal :
To switch to more recent version of the node ie, v16.17.0, use the following command in the terminal
nvm use v16.17.0
Output in the Terminal :
Now confirm the current version of the node by
node --version
Output in Terminal:
I encountered this when running automated tests with jest and rendering a component that included import { AgGridColumn, AgGridReact } from "ag-grid-react".
The solution is to mock out that function as follows:
jest.mock('ag-grid-react', () => ({
__esModule: true,
AgGridReact: jest.fn((x) => <div>{x.children}</div>),
AgGridColumn: jest.fn(() => <div />),
}));
I was getitng the same error after adding the mongodb, i resolve it by upgrading to node version
nvm use 16.16.0
TextEncoder is native function in javascript, check the version that suit the ability.
https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder#browser_compatibility
Chrome version >=38, Edge version >=79, Firefox version >=18, Node verison >=11.0.0...

Categories

Resources