Node.JS "Uncaught TypeError: util.TextEncoder is not a constructor"

Viewed 4324

I have used browserify to bundle up my js files. I get an error of the form

Uncaught TypeError: util.TextEncoder is not a constructor
    at Object.1.util (bundle.js:3)
    at o (bundle.js:1)
    at r (bundle.js:1)
    at bundle.js:1

Here are my initial few lines of bundle.js

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var util = require('util');
var utf8 = new util.TextEncoder();

let secretDataTxt=document.querySelector(`#SecretData`);
let passwordTxt=document.querySelector(`#Password`);
let result=document.querySelector(`#Result`);

let encryptBtn=document.querySelector(`#encrypt`);

Can someone please help me with this error?

EDIT: Here is a working example

const util = require('util');
const utf8 = new util.TextEncoder();

console.log(utf8.encode("Hello"));

Output: Uint8Array(5) [ 72, 101, 108, 108, 111 ]

1 Answers

Try by running npm install text-encoding

and paste this code wherever it gives you the error:

const TextEncodingPolyfill = require('text-encoding');
Object.assign(global, {
  TextEncoder: TextEncodingPolyfill.TextEncoder,
  TextDecoder: TextEncodingPolyfill.TextDecoder,
});


const encoder = new TextEncoder();
const decoder = new TextDecoder();
Related