44

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(); 
    });
}
nmaier
  • 32,336
  • 5
  • 63
  • 78

21 Answers21

59

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");

vivek pawar
  • 639
  • 3
  • 4
30

In nodejs you can solve with util:

var util= require('util');
var encoder = new util.TextEncoder('utf-8');
Diep Gepa
  • 515
  • 5
  • 5
18

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

Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116
14
  1. 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

  2. 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
    
Sahil Thummar
  • 1,926
  • 16
  • 16
5

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");
nmaier
  • 32,336
  • 5
  • 63
  • 78
5

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

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • 4
    This would be a problem if you ever need to reinstall npm packages or update etc. How will you track this change? – Suraj Rao Sep 09 '21 at 14:15
  • 1
    What? manually change the file in dist folder? How is this going to work in a clean deployment where everything is rebuilt? – dragonfly02 Aug 23 '22 at 03:04
3

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.

Gilbert
  • 2,699
  • 28
  • 29
2

For me upgrade Node.js version resolved this issue

2

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.

1

The TextEncoder can be found in the sdk/io/buffer module:

let { TextEncoder, TextDecoder } = require('sdk/io/buffer')
jsantell
  • 1,268
  • 8
  • 10
1

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
Muhammad Ali
  • 100
  • 5
1

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.

1

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.

  1. Update node to 14 or higher, I used Node Version Manager (NVM)

  2. Delete node_modules directory, on linux:

    rm -rf node_modules

  3. Install dependencies with npm install

  4. Close and open a new terminal

  5. Run app with node or nodemon

Done!

Ivandez
  • 249
  • 6
  • 13
1

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

Zaid Bin Khalid
  • 748
  • 8
  • 25
1

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 />),
}));
fredrivett
  • 5,419
  • 3
  • 35
  • 48
0

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

Raja
  • 451
  • 5
  • 5
0

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

0

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.

James Risner
  • 5,451
  • 11
  • 25
  • 47
Sect0R
  • 31
  • 2
0

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 :

enter image description here

The following command will list the different node versions already installed in your system.

nvm ls

Output in the Terminal :

enter image description here

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 :

enter image description here

Now confirm the current version of the node by

node --version

Output in Terminal:

enter image description here

Madhu Tomy
  • 662
  • 11
  • 25
0

I was getitng the same error after adding the mongodb, i resolve it by upgrading to node version

nvm use 16.16.0
AbdulBasit
  • 1,269
  • 11
  • 19
-2

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...

gogog
  • 410
  • 5
  • 9