hildjj / node-cbor

Encode and decode CBOR documents, with both easy mode, streaming mode, and SAX-style evented mode.
MIT License
357 stars 73 forks source link

REACT TypeError: TextDecoder is not a constructor #135

Closed yairvillarpt closed 3 years ago

yairvillarpt commented 3 years ago

Hi im having this problem where im calling cbor-web from react and when i run jest it gives me this error TypeError: TextDecoder is not a constructor im importing it this way const cbor = require('cbor-web'); and the weird part is that when i do import cbor from 'cbor-web' cbor will not get loaded and the const cbor is undefined.

does anyone got any clues??

here is my code:

const cbor = require('cbor-web');
import EventEmitter from 'react-native/Libraries/vendor/emitter/EventEmitter';

let FlircHidApiEventEmitter = new EventEmitter();

let websocketConnector = {
    socket: null,
    server: null,
    closing: null,
    EventEmitter: FlircHidApiEventEmitter,
    DisconnectDevice: ()=>{
        if (websocketConnector.socket){
            console.log('disconnecting');//FIXME: replace to logging
            websocketConnector.socket.close();
            websocketConnector.socket._eventEmitter.removeAllListeners('websocketMessage');
            websocketConnector.socket = null;
        }
        return {msg: 'disconnected', response_code: 0};
    },
    GetDevices: ()=>{
        const devices = [
            'ws://echo.websocket.org',
            'ws://localhost:20000',
            'ws://localhost:21000',
            'ws://localhost:22000'];
        return {msg: `HID devices found: ${devices.length}`, devices: devices};
    },
    ConnectToDevice: async (url)=>{
        websocketConnector.server = url;
        try {
            const socket = await websocketConnector.connect();
            websocketConnector.socket = socket;
            return {msg: 'Connected', response_code:0};
        } catch (error) {
            console.log('Socket Error: ', error.message);//FIXME: replace to logging
            return {msg: 'Connection Error', response_code:1};
        }
    },
    SendCommand: (payload) => {
        websocketConnector.socket.send(payload);
        return {msg: 'sent', response_code:0};
    },

    connect(){
        return new Promise(function(resolve, reject) {
            var socket = new WebSocket(websocketConnector.server);
            socket.onclose = function() {
                console.log('Connection Closed');//FIXME: replace to logging
            };
            socket.onopen = function() {
                console.log('On Open');//FIXME: replace to logging
                resolve(socket);
            };
            socket.onerror = function(err) {
                console.log('onerror: ', err);//FIXME: replace to logging
                reject(err);
            };
            socket.onmessage = async function(e){
                console.log( websocketConnector.socket._eventEmitter);
                const buffer = new Uint8Array(e.data);
                const hex = Array.prototype.map.call(buffer, x => ('00' + x.toString(16)).slice(-2)).join('').split('ffff');
                const decoded = await cbor.decodeFirst(hex[0]);
                websocketConnector.EventEmitter.emit('GetResponseEvent', JSON.stringify(decoded));
            };
        });
    },
};

export default websocketConnector;
hildjj commented 3 years ago

First off, you can pass a Uint8Array in directly now, instead of converting to hex first. Next, what browser and version? I thought everything vaguely modern had TextDecoder now. Maybe it needs a window.

yairvillarpt commented 3 years ago

the problem is in the first line the require, im using react native, nodejs 12.18.3

hildjj commented 3 years ago

Ok, I'll look into this later; I did test cbor-web with 12, but I'm not sure of the sub-version. Likely not l will need to bring back the fallback to util.TextDecoder. It may take a few days due to some other things going on, but I'll prioritize getting you a fix.

Can you try with node 14 once, in the meantime? That's not a fix, just a datapoint for me.

yairvillarpt commented 3 years ago

Yeap, no prob, im gonna try, ill let you know if it works, thanks

hildjj commented 3 years ago

I'm going to leave this open until you verify it fixes the problem in your environment. I don't think it should have been possible for this to have failed like this in node 12, but it made it fail in node 10, then took an aggressive approach to prevent the problem in the future.

Please try with v7.0.3 which i just published.

hildjj commented 3 years ago

I'm going to assume this worked for you @yairvillarpt. If not, please re-open this issue.