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 :)
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
}
});
Since iojs merged into Node. I assumed I can run koajs without the --harmony tag (because it'll have generators from es6 supported).
So within my server.js file I have:
var koa = require('koa');
var app = koa();
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);
My package.json file has "koa": "^1.1.2".
I run node server.js and get:
app.use(function *(){
^
SyntaxError: Unexpected token *
Any ideas why it's complaining? Do I still need to use the --harmony tag?
Thanks!
I'm surprised I didn't come across more questions about this on the web. Anyway, i've got it to work without the --harmony flag.
At the moment they're working on V2.* which has ES6 support. You can find it on their git repo under V2 branch https://github.com/koajs/koa.
So you need to npm install koa#next -save to grab the latest which currently is "koa": "^2.0.0-alpha.3".
To make sure it's working you can quickly throw this in an index.js file then run node index.js:
const Koa = require('koa');
const app = new Koa();
// logger
app.use((ctx, next) => {
const start = new Date;
return next().then(() => {
const ms = new Date - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
V2 once stable will be merged into the master branch and just npm install koa will work. But for what I wanted, npm install koa#next -save worked fine :)
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...
I followed the github meteorirc project's lead and put them in /public/
I installed my node modules via npm from inside /public/ and therefore I have a /public/node_modules/ directory.
I don't think this is the 'proper' or 'standard' place for them because according to the Meteor docs...
Meteor gathers all your JavaScript files, excluding anything under the
client and public subdirectories, and loads them into a Node.js server
instance inside a fiber
The code to load is in the server dir and server js files and looks like this.
var require = __meteor_bootstrap__.require;
var path = require("path");
var fs = require('fs');
var base = path.resolve('.');
if (base == '/'){
base = path.dirname(global.require.main.filename);
}
var Twit;
var twitPath = 'node_modules/twit';
var publicTwitPath = path.resolve(base+'/public/'+twitPath);
var staticTwitPath = path.resolve(base+'/static/'+twitPath);
if (path.existsSync(publicTwitPath)){
Twit = require(publicTwitPath);
}
else if (path.existsSync(staticTwitPath)){
Twit = require(staticTwitPath);
}
else{
console.log('WARNING Twit not loaded. Node_modules not found');
}
Based on the docs this is not standard and I don't believe I should be doing it this way. Yet, it works both on my dev platform and in production at deploy meteor.com.
Where in the directory structure of the project should node modules be installed so that they work locally and upon deployment at meteor.com or elsewhere?
cd /usr/local/meteor/lib/ && npm install <module>
To use Npm modules in Meteor its adding the npm module in.
First you need to add a npm package adapter such as meteorhacks:npm
meteor add meteorhacks:npm
Then start your meteor app by running meteor, you will notice a new packages.json file in your project
Add in modules like this (you need to explicitly define a version)
{
"request" : "2.53.0"
}
Then you can use the npm modules in your meteor app, use Meteor.npmRequire instead of require
var request = Meteor.npmRequire("request")
Meteor takes lib/node_modules from the development bundle and makes a symbolic link or copies it to server/node_modules, which is in the hidden .meteor sub folder under your project.
So, if you cd into the lib directory of the development bundle or into server directory of the .meteor folder (I believe it is in build); you will be able to use the node modules. If you have trouble loading them, you might want to check out this question.
You have to add bundle folder to the path:
var staticTwitPath = path.resolve(base+'/bundle/static/'+twitPath);
Here is my working sample in coffeescript, node_modules are in public folder:
# loading node_modules from public folder
require = __meteor_bootstrap__.require
path = require("path")
fs = require('fs')
cheerioPath = 'node_modules/cheerio'
base = path.resolve('.')
if base == '/'
base = path.dirname(global.require.main.filename)
publicPath = path.resolve(base+'/public/'+cheerioPath)
staticPath = path.resolve(base+'/bundle/static/'+cheerioPath)
if path.existsSync(publicPath)
cheerio = require(publicPath)
else if path.existsSync(staticPath)
cheerio = require(staticPath)
else
console.log('node_modules not found')
Good luck!
This helped me a lot including a syntax highlighting package! Thanks!
I use a little helper though, as I think this will not be the last npm package I'll use ;)
meteorNpm = do() ->
require = __meteor_bootstrap__.require
path = require 'path'
fs = require 'fs'
base = path.resolve '.'
if base is '/'
base = path.dirname global.require.main.filename
meteorNpm =
# requires npm modules placed in `public/node_modules`
require: (moduleName) ->
modulePath = 'node_modules/' + moduleName
publicPath = path.resolve(base + '/public/' + modulePath)
staticPath = path.resolve(base + '/bundle/static/' + modulePath)
if path.existsSync(publicPath)
module = require publicPath
else if path.existsSync(staticPath)
module = require staticPath
else
module = null
return module
Use it like this:
highlight = meteorNpm.require "highlight.js"
I am using such script which nicely install all node.js dependencies. It behaves similar to official support in Meteor engine branch (it installs dependencies at runtime) but it supports also installing from git repositories and similar goodies.