Deno.env is not a function - javascript

Working on short tutorial with deno and postgres from https://blog.logrocket.com/creating-your-first-rest-api-with-deno-and-postgres/
I had an error within my config.js file:
const env = Deno.env();
export const APP_HOST = env.APP_HOST || "127.0.0.1";
export const APP_PORT = env.APP_PORT || 4000;
Running deno command I got the error:
$ deno run -A index.js
error: Uncaught TypeError: Deno.env is not a function
const env = Deno.env();

That blog post is using an older version of Deno, where Deno.env() was a function.
It was changed for 1.0.0 release. Deno.env is now an object with: .set , .get, .toObject methods.
So to get an env variable you do:
Deno.env.get('MY_VARIABLE');
Deno introduced a lot of breaking changes for 1.0.0 release, so I suggest to avoid using code from tutorials using <1.0.0.

As the error says, Deno.env isn't a function. So you don't use () on it. It's an object, you use it directly:
const env = Deno.env;

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.

Why can't I modify module.exports? Why does my browser complain after no problems from `npm run build`?

Why doesn't the browser let me do:
Getters.js
let Getters = {}
Getters.foo = function(){ return 1; }
Getters.bar = function(){ return 2; }
module.exports = Getters;
But after npm run build and serve -s build -l 4000, I get the error message:
Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
at Module.<anonymous> (Getters.js:954)
Is there an easy way to resolve this?
Have you imported any module with es6 import statement? If yes, try updating to common js module. Don't mix up es6 and commonJS import statements.
es6
import a from '/a.js';
commonJS
const a = require('/a.js');

PubNub Node util.inherit is not a function

After adding the pubnub node sdk to my nativescript Project
npm install pubnub
I get following error message:
> System.err: Error: Parsing XML at 58:9 System.err: > util.inherits is
> not a function
I simply require it like this:
const PubNub = require("pubnub");
Any idea how that could happen?
Currently, PubNub Node SDK is not compatible with NativeScript v5. It is compatible with NativeScript v3. PubNub is investigating changes that can be made to be compatible with NativeScript v5.
Workaround by #Jon_not_doe_xx:
In the webpack.config.js file, add this in the head:
const shims = require('nativescript-nodeify/shims.json');
const aliases = {};
for (const key of Object.keys(shims)) {
const value = shims[key];
aliases[key + '$'] = value;
}
aliases['inherits$'] = 'inherits/inherits_browser';
// Remove hook, as this will only cause problems at this point.
// Checking and deleting within webpack ensures
// that it will be deleted during a cloud build.
let fs = require("fs");
let process = require("process");
if (fs.existsSync(__dirname + "/hooks/after-prepare/nativescript-nodeify.js")) {
process.stdout.write("Found evil hook, deleting...\n");
fs.unlinkSync(__dirname + "/hooks/after-prepare/nativescript-nodeify.js");
process.stdout.write("Should be fixed now.\n");
}
else process.stdout.write("Hooks seem clean, moving on.\n");
Also, modify the alias object inside the resolve object in the webpack.config.js file:
alias: {
'~': appFullPath,
'#': appFullPath,
...aliases
},

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