Unhandled promise rejection: ReferenceError: Can't find variable: indexedDB - javascript

I'm trying to set up a Back4App backend in a react native expo 45 app. I keep getting a
[Unhandled promise rejection: ReferenceError: Can't find variable: indexedDB]
warning related to the async-storage and Parse import.
import AsyncStorage from "#react-native-async-storage/async-storage";
const Parse = require("parse/react-native.js");
Parse.setAsyncStorage(AsyncStorage);
The warning points to a function in
node_modules\parse\node_modules\idb-keyval\dist\compat.cjs
function createStore(dbName, storeName) {
var dbp = safariFix__default['default']().then(function () {
var request = indexedDB.open(dbName);
request.onupgradeneeded = function () {
return request.result.createObjectStore(storeName);
};
return promisifyRequest(request);
});
return function (txMode, callback) {
return dbp.then(function (db) {
return callback(db.transaction(storeName, txMode).objectStore(storeName));
});
};
}
I find almost no results with searches so I don't even know where to begin troubleshooting. Am I missing something or can this just be ignored?

The problem is in Parse#3.4.2
I reverted back to Parse#3.4.0 and all is working again for now.

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

require node-pty results in TypeError: Object.setPrototypeOf: expected an object or null, got undefined

TL;DR: If I try to do var pty = require('node-pty'); results in TypeError: Object.setPrototypeOf: expected an object or null, got undefined keep reading for context
Hi, I'm trying to build a proof of concept by creating a terminal using React. For that, I used xterm-for-react which I made it work fine, and node-pty with this last library is with the one I'm having problems.
Initially I created a file in which I would try to make calls to it, it looks like this:
var os = require('os');
var pty = require('node-pty');
var shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
var ptyProcess;
function createNewTerminal(FE){
ptyProcess = pty.spawn(shell, [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});
ptyProcess.onData((data) => FE.write(data));
}
function writeOnTerminal(data){
ptyProcess.write(data);
}
module.exports = {
createNewTerminal,
writeOnTerminal
}
I know it may not be the best code out there, but I was doing it just to try to see if this was possible. My plan was to call the functions from the react component like this:
import {createNewTerminal, writeOnTerminal} from './terminal-backend';
function BashTerminal() {
const xtermRef = React.useRef(null)
React.useEffect(() => {
// You can call any method in XTerm.js by using 'xterm xtermRef.current.terminal.[What you want to call]
xtermRef.current.terminal.writeln("Hello, World!")
createNewTerminal(xtermRef.current.terminal)
}, [])
const onData = (data) => {
writeOnTerminal(data);
}
return (
<XTerm ref={xtermRef} onData={onData}/>
);
}
But I was surprised that this was not working, and returned the error in the title. So, in order to reduce noise, I tried to change my functions to just console logs and just stay with the requires. My file now looked like this:
var os = require('os');
var pty = require('node-pty');
function createNewTerminal(FE){
console.log("Creating new console");
}
function writeOnTerminal(data){
console.log("Writing in terminal");
}
module.exports = {
createNewTerminal,
writeOnTerminal
}
Still got the same error. I'm currently not sure if this is even possible to do, or why this error occurs. Trying to look things online doesn't give any results, or maybe it does and I'm just not doing it right. Well, thanks for reading, I'm completely lost, so, if someone knows something even if it's not the complete answer I will be very thankful

Unable to parse page text, getting "ReferenceError: ReadableStream is not defined"

I am currently trying to create a util to parse annotations from a PDF. I can load the PDF file just fine, the annotation objects just fine, but I need to obtain the text that is related to those annotations (underlined, highlighted, etc.).
This gets hairy when I try to use the getTextContent() method which fails. Below is the method where this happens:
/**
* #param pdf The PDF document obtained upon `pdfjs.getDocument(pdf).promise` success.
*/
function getAllPages(pdf) {
return new Promise((resolve, reject) => {
let allPromises = [];
for (let i = 0; i < numPages; i++) {
const pageNumber = i + 1; // note: pages are 1-based
const page = pdf.getPage(pageNumber)
.then((pageContent) => {
// testing with just one page to see what's up
if (pageNumber === 1) {
try {
pageContent.getTextContent()
.then((txt) => {
// THIS NEVER OCCURS
console.log('got text');
})
.catch((error) => {
// THIS IS WHERE THE ERROR SHOULD BE CAUGHT
console.error('in-promise error', error)
});
} catch (error) {
// AT LEAST IT SHOULD BE CAUGHT HERE
console.log('try/catch error:', error);
}
}
})
.catch(reject);
allPromises.push(page);
}
Promise.all(allPromises)
.then(() => {
allPagesData.sort(sortByPageNumber);
resolve(allPagesData);
})
.catch(reject);
});
}
When calling pageContent.getTextContent(), which should return a promise, the error "ReferenceError: ReadableStream is not defined" is thrown in the catch() part of the try.
This is weird because I would have expected the pageContent.getTextContent().catch() to be able to, well, catch that. Also, I don't know what to do to resolve this.
Any help is appreciated.
I have noticed that using pdfjs-dist causes the error.
Use pdfjs-dist/es5/build/pdf.js instead.
const pdfjs = require('pdfjs-dist/es5/build/pdf.js');
Update:
const pdfJs = require('pdfjs-dist/legacy/build/pdf')
Example usage
There was a new change, the only way it worked here was to use this path:
const pdfJs = require('pdfjs-dist/legacy/build/pdf')
I started a new project with pdfjs-dist and got the same ReadableStream error at getTextContent. Also i have an older project with the same lib that works fine. So, when I downgraded to an older version (2.0.943 to be precise) the error was gone. I don't realy know why. Hope that helps.

Get multiples database on the same server

I use AdonisJS and MSSQL. I have some databases on the same server : https://i.imgur.com/d4Eqfpt.png
In my .env I have this configuration :
DB_CONNECTION=mssql
DB_HOST=127.0.0.1
DB_PORT=1433
DB_USER=sa
DB_PASSWORD=123456
DB_DATABASE=WEB_PANEL
The problem is, i have my own API to make requests like that :
connectToDatabase('mssql://id:pw#localhost').then(async () => {
let onlinePlayers = await User.getOnlinePlayers()
let numberOfStaff = staff.length
let numberOfOnlinePlayers = onlinePlayers.recordset.length
return view.render('system.index', { totalPlayers: numberOfOnlinePlayers, numberOfStaff: numberOfStaff })
})
}
And I have this error :
warning:
warning:
WARNING: Adonis has detected an unhandled promise rejection, which may
cause undesired behavior in production.
To stop this warning, use catch() on promises or wrap await
calls inside try/catch.
TypeError: Cannot read property 'substr' of null
at parseConnectionURI (C:\Users\didi\Desktop\drpanel\panel\node_modules\mssql\lib\connectionstring.js:21:32)
at Object.resolveConnectionString [as resolve] (C:\Users\didi\Desktop\drpanel\panel\node_modules\mssql\lib\connectionstring.js:205:72)
at new ConnectionPool (C:\Users\didi\Desktop\drpanel\panel\node_modules\mssql\lib\base.js:127:40)
at new ConnectionPool (C:\Users\didi\Desktop\drpanel\panel\node_modules\mssql\lib\tedious.js:175:1)
at Object.connect (C:\Users\didi\Desktop\drpanel\panel\node_modules\mssql\lib\base.js:1592:22)
at connectToDatabase (C:\Users\didi\Desktop\drpanel\panel\drapi\src\core\connection.handler.js:4:15)
at SystemController.showSystemPage (C:\Users\didi\Desktop\drpanel\panel\app\Controllers\Http\Panel\SystemController.js:8:9)
at Server._routeHandler (C:\Users\didi\Desktop\drpanel\panel\node_modules\#adonisjs\framework\src\Server\index.js:121:31)
at MiddlewareBase._resolveMiddleware (C:\Users\didi\Desktop\drpanel\panel\node_modules\#adonisjs\middleware-base\index.js:195:28)
at Runnable._invoke (C:\Users\didi\Desktop\drpanel\panel\node_modules\co-compose\src\Runnable.js:76:42)
at C:\Users\didi\Desktop\drpanel\panel\node_modules\co-compose\src\Runnable.js:73:34
at f (C:\Users\didi\Desktop\drpanel\panel\node_modules\once\once.js:25:25)
at Authenticated.handle (C:\Users\didi\Desktop\drpanel\panel\app\Middleware\Authenticated.js:16:19)
at async ConvertEmptyStringsToNull.handle (C:\Users\didi\Desktop\drpanel\panel\app\Middleware\ConvertEmptyStringsToNull.js:13:5)
at async AuthInit.handle (C:\Users\didi\Desktop\drpanel\panel\node_modules\#adonisjs\auth\src\Middleware\AuthInit.js:60:5)
at async Shield.handle (C:\Users\didi\Desktop\drpanel\panel\node_modules\#adonisjs\shield\src\Shield\index.js:417:5)
And for example getOnlinePlayers() is :
static async getOnlinePlayers() {
let onlinePlayers = await sql.query`
USE DR2_USER
SELECT TOP 10 * FROM TB_CharacterSub
WHERE f_ConnectionChannel != 0`
return onlinePlayers
}
For example I want to use the DR2_USER database but i can't :/
Please someone has a solution ?
Thanks !
You can edit your config/database.js to configure multiple database connections and set the Lucid Model to use that connection
https://adonisjs.com/docs/4.1/lucid#_connection
class User extends Model {
static get connection () {
return 'mysql'
}
}

knex.js - reading then updating throws an Error

I'm trying to chain read and update operations. First I read (fetch) data from the database based on the id, then I change it and want to update the data in the database as well but I get a Unhandled rejection Error: There is no pool defined on the current client error.
index.js
var id = args.id;
var proj = new Project(id);
proj.read(knex).then(function(rows) {
proj.set(args);
proj.update(knex).then(console.log); // <== ERROR THROWN HERE
});
Project.js (only related functions)
read(knex) {
var self = this;
return knex('projects').where('id', this.id).then(function(rows) {
if (rows.length == 0)
throw '[panda] Read project: no project with id = ' + self.id;
self.set(rows[0]);
return self;
});
}
update(knex) {
console.log(knex('projects').where('id', this.id).update(this).toString());
return knex('projects').where('id', this.id).update(this);
}
Command
$ node index.js projects update --id=5 --name=Test-update
update "projects" set "completion" = 0, "currentIteration" = NULL, "id" = 5, "name" = 'Test-update' where "id" = 5
Unhandled rejection Error: There is no pool defined on the current client
at /home/flawyte/development/projects/js/panda/node_modules/knex/lib/client.js:202:25
at tryCatcher (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/util.js:26:23)
at Promise._resolveFromResolver (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/promise.js:480:31)
at new Promise (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/promise.js:70:37)
at Client.acquireConnection (/home/flawyte/development/projects/js/panda/node_modules/knex/lib/client.js:200:12)
at /home/flawyte/development/projects/js/panda/node_modules/knex/lib/runner.js:136:49
at tryCatcher (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/util.js:26:23)
at Function.Promise.attempt.Promise.try (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/method.js:31:24)
at Runner.ensureConnection (/home/flawyte/development/projects/js/panda/node_modules/knex/lib/runner.js:135:26)
at Runner.run (/home/flawyte/development/projects/js/panda/node_modules/knex/lib/runner.js:30:31)
at QueryBuilder.Target.then (/home/flawyte/development/projects/js/panda/node_modules/knex/lib/interface.js:27:43)
at /home/flawyte/development/projects/js/panda/index.js:80:31
at tryCatcher (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/util.js:26:23)
at Promise._settlePromiseFromHandler (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/promise.js:507:31)
at Promise._settlePromiseAt (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/promise.js:581:18)
at Promise._settlePromises (/home/flawyte/development/projects/js/panda/node_modules/bluebird/js/main/promise.js:697:14)
If I remove the then(console.log) in index.js no error is thrown but data in database remains unchanged after script ending. Why ?
I had a line knex.destroy(); at the very end of my script and as knex is asynchronous, the line was being executed after the read() instruction (due to quick execution) but before update(), causing the error above.
Project.js
var done = false;
proj.read(knex).then(function(rows) {
proj.set(args);
proj.update(knex).then(function(res) {
done = true;
console.log(res);
knex.destroy();
});
});
// ...
if (!done)
// End database connection here
// in case an error prevented it from being destroyed after update
// which would in turn prevent the script from ending
knex.destroy();

Categories