How to Define TextdecoderStream and TextEncoderStream while using Web Serial in react? - javascript

My code is like this in react when i run it, it says TextDecoderStream() & TextEncoderStream() is not defined.
async function connect() {
const port = await navigator.serial.requestPort();
// - Wait for the port to open.
await port.open({ baudRate: 115200 });
console.log("Open");
let decoder = new TextDecoderStream();
inputDone = port.readable.pipeTo(decoder.writable);
inputStream = decoder.readable;
const encoder = new TextEncoderStream();
outputDone = encoder.readable.pipeTo(port.writable);
outputStream = encoder.writable;
let reader = inputStream.getReader();
}
getting error
src\Components\play\Remote\Ace\RemoteSection\RemoteSection.js
Line 453:23: 'TextDecoderStream' is not defined no-undef
Line 457:25: 'TextEncoderStream' is not defined no-undef
And if i remove stream and only use TextDecoder() and TextEncoder()
then it is showing
Unhandled Rejection (TypeError): Failed to execute 'pipeTo' on
'ReadableStream': parameter 1 is not of type 'WritableStream'.
Unhandled Rejection (TypeError): Cannot read properties of undefined
(reading 'pipeTo')

TextDecoderStream and TextEncoderStream are available in Chrome 71 according to https://chromestatus.com/features/4881011259211776.
I suspect your issue is a linter issue. You may want to try this eslint rule as documented at https://eslint.org/docs/rules/no-undef.
// eslint-disable-next-line no-undef
let decoder = new TextDecoderStream();
...
// eslint-disable-next-line no-undef
const encoder = new TextEncoderStream();

Related

Why am I getting "Cannot access 'server' before initialization" error in NodeJS?

I am getting the dreaded Cannot access 'server' before initialization error in code that is identical to code that's running in production.
The only things that have changed are my OS version (macOS 10.11->10.14) my NodeJS version (10->12) and my VSCode launch.json, but I cannot see anything in either that would cause an issue. My Node version went from 10 to 12, but in production it went from 8 to 15 without issue. I routinely keep launch.json pretty sparse, and the same error happens using node server in Terminal.
Here is the offending code. The issue occurs because I have shutdown() defined before server and it references server. It's written to add an event-handler and then cause the event. Yes, it could be refactored but it already works. It works, really. In 21 instances spread over 7 servers.
I have tried changing the declaraion/init of server from const to var but that does not fix it. As mentioned, this is code that's running in prod! What's wrong with my environment?
Maybe a better question is: why did this ever work?
'use strict'
const fs = require('fs');
const https = require('https');
const cyp = require('crypto').constants;
const stoppable = require('./common/stoppable.js');
const hu = require('./common/hostutil');
process.on('uncaughtException', err => {
wslog.error(`Uncaught Exception: ${err} ${err.stack}`);
shutdown();
});
process.on('unhandledRejection', (reason, p) => {
wslog.error(`Unhandled Promise Rejection: ${reason} - ${p}`);
});
// 'shutdown' is a known static string sent from node-windows wrapper.js if the service is stopped
process.on('message', m => {
if (m == 'shutdown') {
wslog.info(`${wsconfig.appName} has received shutdown message`);
shutdown();
}
});
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
process.on('SIGHUP', shutdown);
function shutdown() {
httpStatus = 503; // Unavailable
wslog.info(`${wsconfig.appName} httpStatus now ${httpStatus} - stopping server...`);
// Error happens on this next line; It should not execute till after server is running already
server.on('close', function () {
wslog.info(`${wsconfig.appName} HTTP server has stopped, now exiting process.`);
process.exit(0)
});
server.stop();
}
// Init and start the web server/listener
var combiCertFile = fs.readFileSync(wsconfig.keyFile, 'utf8');
var certAuthorityFile = fs.readFileSync(wsconfig.caFile, 'utf8');
var serverOptions = {
key: combiCertFile,
cert: combiCertFile,
ca: certAuthorityFile,
passphrase: wsconfig.certPass,
secureOptions: cyp.SSL_OP_NO_TLSv1 | cyp.SSL_OP_NO_TLSv1_1
};
var server = https.createServer(serverOptions, global.app)
.listen(wsconfig.port, function () {
wslog.info(`listening on port ${wsconfig.port}.`);
});
server.on('clientError', (err, socket) => {
if (err.code === 'ECONNRESET' || !socket.writable) { return; }
// ECONNRESET was already logged in socket.on.error. Here, we log others.
wslog.warn(`Client error: ${err} ${err.stack}`);
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.on('error', (err)=>{
if ( err.code === 'EADDRINUSE' ) {
wslog.error(`${err.code} FATAL - Another ${wsconfig.appName} or app is using my port! ${wsconfig.port}`);
} else {
wslog.error(`${err.code} FATAL - Server error: ${err.stack}`);
}
shutdown();
})
combiCertFile = null;
certAuthorityFile = null;
// Post-instantiation configuration required (may differ between apps: need an indirect way to plug in app-specific behavior)
stoppable(server, wsconfig.stopTimeout);
// Load all RESTful endpoints
const routes = require('./routes/');
This is a runtime error, which happens only in a very specific situation. But actually this exact error shouldn't happen with var server = ... but only with const server = ... or let server = .... With var server = ... the error message should say "Cannot read properties of undefined"
What happens
You have an error handler for uncaughtException which is calling shutdown() and in shutdown() you are referencing your server. But consider what happens if your code throws an exception before you initialized your server. For instance if your cert or key cannot be read from the disk, cert or key are invalid ... So nothing will be assigned to server, and an exception will be raised.
Then the handler for your uncaught exception will fire and call the shutdown() function, which then tries to access the server, which of course hasn't been initialized yet.
How to fix
Check what the unhandled exception is, that is thrown before your server is initialized and fix it. In your production environment, there is probably no exception, because the configuration and environment is properly set up. But there is at least one issue in your develepment environment, which causes an exception.
Difference between var and const
And the difference between var server = ... and const server = ... is quite a subtle one. For both, the declaration of the variable is hoisted up to the top of their respective scope. In your case it's always global, also for const. But variables declared as var are assigned a value of undefined whereas variables declared as let/const are not initialized at all.
You can easily reproduce this error if you uncomment either error1 or error2 in the following code. But error3 alone won't produce this ReferenceError because bar will already be initialized. You can also replace const bar = with var bar = and you will see, that you get a different error message.
process.on("uncaughtException", err => {
console.log("uncaught exception");
console.log(err);
foo();
});
function foo() {
console.log("foo");
console.log(bar.name);
}
function init() {
// throw new Error("error1");
return { name: "foobar"}
}
// throw new Error("error2");
const bar = init();
//throw new Error("error3");

Transfer error using Phantom Wallet when using signAndSendTransaction function

Does anyone know what's wrong with this code?
await window.solana.connect();
let fromWallet = window.solana.publicKey;
let toWallet = new PublicKey("<KEY>");
let transaction = new Transaction();
transaction.add(
SystemProgram.transfer({
fromPubKey: fromWallet,
toPubKey: toWallet,
lamports: LAMPORTS_PER_SOL
})
);
transaction.feePayer = fromWallet;
const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
let bk = await connection.getLatestBlockhash();
transaction.recentBlockhash = bk.blockhash;
const signature = await window.solana.signAndSendTransaction(await transaction);
await connection.confirmTransaction(signature);
console.log(signature);
It throws an error at line
const signature = await window.solana.signAndSendTransaction(await transaction)
Something about converting undefined to base58.
I have checked the keys, they are both fine.
Here is the error log:
vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading 'toBase58')
at eval (index.browser.esm.js?64b9:2451:1)
at Array.sort (<anonymous>)
at Transaction.compileMessage (index.browser.esm.js?64b9:2450:1)
at Transaction._compile (index.browser.esm.js?64b9:2563:1)
at Transaction.serializeMessage (index.browser.esm.js?64b9:2585:1)
at ia (inpage.js:141:130205)
at inpage.js:141:137033
at c (inpage.js:2:47880)
at Generator._invoke (inpage.js:2:47668)
at Generator.next (inpage.js:2:48309)
Any ideas?
Oh dear lord,
I fixed the issue by changing the code:
transaction.add(
SystemProgram.transfer({
fromPubKey: fromWallet,
toPubKey: toWallet,
lamports: LAMPORTS_PER_SOL
})
);
to the following:
const instruction = SystemProgram.transfer({
fromPubkey: fromWallet,
toPubkey: toWallet,
lamports: LAMPORTS_PER_SOL,
});
transaction.add(instruction);
I still don't understand why it works, but hey it solved my issue.
The error TypeError: Cannot read properties of undefined (reading 'toBase58') typically means that there's an invalid PublicKey somewhere.
Assuming that the connection to the wallet is correct, there's probably an issue with the line:
let toWallet = new PublicKey("<KEY>");
First, be sure that the result of that call is correct, by logging it, ie.:
console.log(toWallet.toBase58());
If that works, then there's likely an issue with the wallet connection.

How to solve javascript "Unhandled Promise Rejection" and "Property 'p' doesn't exist" errors?

I'm working on a game using spark ar, by following the tutorial from youtube (blinking game tutorial).
apparently when I was working there was an error in the script
const Scene = require('Scene');
export const Diagnostics = require('Diagnostics');
const Patches = require("Patches");
Promise.all([
Scene.root.findFirst('number'),]).then(onReady);
function onReady(assets) {
var counterNumber = assets[0];
var scoreNumber = p.outputs.getScalar("score");
scoreNumber.then(e => {
e.monitor().subscribe(value => {
counterNumber.text = value.newValue.toString();
});
});
}
Error : Possible Unhandled Promise Rejection: ReferenceError: Property 'p' doesn't exist
create a const P as below and check whether its working or not
const Scene = require('Scene');
const P = require('Patches');
reference taken from Score Didnt show up (Spark AR)
the problem is on this line :
var scoreNumber = p.outputs.getScalar("score");
"p" is not defined anywhere in your entire code that's why it is throwing error

Javascript- Getting an uncaught type error

Creating a tic tac toe game, but for some reason, I'm getting an uncaught type error when doing observer.observe.
Here is the line where the error is occurring:
board.positions.forEach((el) => observer.observe(el,config));
Here is the function it is occurring in:
function TicTacToeGame() {
const board = new Board();
const humanPlayer = new HumanPlayer(board);
const computerPlayer = new ComputerPlayer(board);
let turn = 0;
this.start = function () {
const config = {childlist: true};
const observer = new MutationObserver(()=> takeTurn());
board.positions.forEach((el) => observer.observe(el,config));
takeTurn();
}
What is this error trying to say and what is the best way to resolve it.
Edit:
Here is the error I am getting:
Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': The options object must set at least one of 'attributes', 'characterData', or 'childList' to true.

"cannot read property "id" of null node js

i am trying to convert my old discord bot from node js 6.x.x to 8.x.x, i am also putting the commands in a separate folder to make it look cleaner, the command works on my old bot but not with this bot, i get
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'id' of null
UPDATED CODE STILL RETURNS THE SAME:
var settings = '../settingsConfig/settings.json';
var file = require(settings)
const SteamTotp = require('steam-totp');
const Discord = require('discord.js');
const configS = require('../settingsConfig/ConfigSammy.json');
const configJ = require('../settingsConfig/ConfigJack.json');
const configB = require('../settingsConfig/ConfigBen.json');
module.exports.run = async (bot, message, args) => {
function myFunc(){
var JackCode = SteamTotp.getAuthCode(configJ.sharedSecret);
var BenCode = SteamTotp.getAuthCode(configB.sharedSecret);
var SammyCode = SteamTotp.getAuthCode(configS.sharedSecret);
var codess = new Discord.RichEmbed()
.addField("__**Bens Code:**__", BenCode)
.addField("__**Jacks Code:**__", JackCode)
.addField("__**Sammys Code:**__", SammyCode)
.setColor(0x00FF00)
message.author.send(codess)
}
new myFunc();
};
module.exports.help = {
name: "codes"
}
Looks like the error comes from having message.guild not being defined, there for calling message.guild.id yields the error
The reason you're getting this specific error is since you are using the async keyword, which basically means you are using a promise, but you don't provide a reject method for it, hence UnhandledPromiseRejectionWarning
The error may occur because your MongoDB would not be connected. Try to repair it while installing MongoDB.

Categories