TypeError: Cannot read property 'EventEmitter' of undefined typescript nodejs - node.js

I have a typescript application running on node.
I am using 'EventEmitter' class to emit a change in variable value.
This is my piece of code,
import events from 'events';
public async updateStream(streamContext: string, state: boolean): Promise<string> {
const eventEmitter = new events.EventEmitter();
if (state === true) {
return StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Paused';
} else {
const streamState = StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Active';
eventEmitter.emit('resume');
return streamState;
}
}
public async waitForStreamActive(stream: Stream) {
const eventEmitter = new events.EventEmitter();
// tslint:disable-next-line:no-unused-expression
return new Promise(( resolve ) => {
eventEmitter.on('resume', resolve );
});
}
This piece of code builds fine. But when i run the code, as in execute the operation, I am getting the following error,
error: errorHandler - Apply - Hit Unhandled exception {"timestamp":"2019-04-29T12:33:49.209Z"}
error: errorHandler - Apply - Cannot read property 'EventEmitter' of undefined - TypeError: Cannot read property 'EventEmitter' of undefined
at StreamResource.updateStream (C:\Vertigo\core\reference_platform\dist\index.js:10695:51)
at StreamService.patchStream (C:\Vertigo\core\reference_platform\dist\index.js:22524:40)
at process._tickCallback (internal/process/next_tick.js:68:7) {"timestamp":"2019-04-29T12:33:49.215Z"}
What am I doing wrong?

I've set up minimal project to reproduce it and immediately ts compiler warns me about:
TS1192: Module '"events"' has no default export.
But this seems to work:
import * as EventEmitter from 'events'
new EventEmitter();

Related

TypeError: Cannot read property 'facts' of undefined

I am trying to make a word randomizer, and it gives me this error:
message.channel.send(item.facts);
^
TypeError: Cannot read property 'facts' of undefined
and I don't know how to fix it.
Here is my code:
const Discord = require('discord.js');
module.exports = {
name: 'game',
execute(message, args) {
const gameChanger = require('../text.txt')
const item = gameChanger[Math.floor(Math.random() * gameChanger.length)];
setInterval(() => {
const item = gameChanger[Math.floor(Math.random() * gameChanger.length)];
message.channel.send(item.facts);
}, 5 * 1000);
}
}
Someone please help me
The error indicates that the variable item is undefined. This is probably because you are going out of bounds of the gameChanger array, which is causing undefined to be assigned to item.

Can't get ref on realtime database with emulator

I am trying to attach a listener to realtime database on local emulator with another database selected but it's giving me a weird error.
Here is the code I am using:
const functions = require("firebase-functions");
const handler = async (snapshot, context) => {
console.log(snapshot);
console.log(context);
}
const target = functions.database
.instance("test-db")
.ref("/docs/{docID}")
module.exports = {
create: target.onCreate(handler),
update: target.onUpdate(handler),
delete: target.onDelete(handler),
}
Here is the error that I am getting:
i functions: Beginning execution of "operationsListenerRealtime-update"
! functions: TypeError: Cannot read property 'startsWith' of undefined
at new DataSnapshot (Q:\Projects\test-project\firebase\functions\node_modules\firebase-functions\lib\providers\database.js:270:44)
at RefBuilder.changeConstructor (Q:\Projects\test-project\firebase\functions\node_modules\firebase-functions\lib\providers\database.js:155:28)
at cloudFunction (Q:\Projects\test-project\firebase\functions\node_modules\firebase-functions\lib\cloud-functions.js:133:34)
at C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:592:16
at runFunction (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:579:15)
at runBackground (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:591:11)
at processBackground (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:574:11)
at invokeTrigger (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:649:19)
at handleMessage (C:\Users\duoqu\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:736:15)
at processTicksAndRejections (node:internal/process/task_queues:94:5)
! Your function was killed because it raised an unhandled error.
Clearly I am trying to connect realtime database that is test-db, I also tried writing http://localhost:7002/?ns=test-db but still no luck. I digged deep into the error and saw this thing:
/**
* Interface representing a Firebase Realtime Database data snapshot.
*/
class DataSnapshot {
constructor(data, path, // path will be undefined for the database root
app, instance) {
this.app = app;
if (app && app.options.databaseURL.startsWith('http:')) {
// In this case we're dealing with an emulator
this.instance = app.options.databaseURL;
}
else if (instance) {
// SDK always supplies instance, but user's unit tests may not
this.instance = instance;
}
else if (app) {
this.instance = app.options.databaseURL;
}
else if (process.env.GCLOUD_PROJECT) {
this.instance =
'https://' + process.env.GCLOUD_PROJECT + '.firebaseio.com';
}
this._path = path;
this._data = data;
}
I think the issue may be related to this part of the code
Also the instance function takes parameters like this.
EDIT: I have confirmed that with proper node version it still is giving me the same error.

TypeError: Cannot read property 'then' of null | discord.js

I am trying to make a message tracker and this error shows and I don't know why
Code: messagecounter.js
const db = require('quick.db');
module.exports = {
name: "msgc",
description: "Message Counter",
async run(client, message, args) {
// checking who wants to fetch it
let member = message.mentions.members.first() || message.member; // this checks if they mentioned a members
db.fetch(`messageSent_${member.id}`).then(obj => {
message.channel.send(`**Messages Sent:** \`${obj.value}\``);
});
}
}
Code: bot.js:70:42
client.commands.get(command).run(client, message, args);
Error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'then' of null
at Object.run (C:\Users\Familia\OneDrive\Documents\Other Stuff\Visual Studio code\blade\commands\messagecounter.js:13:45)
at Client.<anonymous> (C:\Users\Familia\OneDrive\Documents\Other Stuff\Visual Studio code\blade\bot.js:70:42)
Any help would be appreciated
Using discord.js v12
After quickly glancing over "quick.db" I couldn't find a method called fetch defined on the db object. "get", however is defined and is perhaps what you meant to use.

Invalid use of type "undefined" as a Firestore argument

I am getting error when I execute my code. Below code used for creating collection in cloud Firestore, before this I didn’t created any collection in cloud Firestore. It is empty. In the console.log, I am getting correct json object.
createEntry(subjectId: string, questionnaire: string, callback: (err: any, response: any) => void) :void {
let testEntity: TestEntity = new TestEntity(subjectId, questionnaire);
console.log("testEntity.toJSON();----------->",testEntity.toJSON());
var docRef = this.dbManager.collection('testQuestion').doc(subjectId);
var setAlan = docRef.set(testEntity.toJSON());
}
Here TestEntity is json values as below. All the fields have values.
public toJSON(): testEntry {
let returnJSON = {
"entry_id": this.entry_id,
"subject_id": this.subject_id,
"entry_date": this.entry_date,
"questionnaire": this.questionnaire,
"entry_start_timestamp": this.entry_start_timestamp,
"entry_end_timestamp": this.entry_end_timestamp,
"entry_complete": this.entry_complete,
"responses": this.responses,
"last_answered_question" : this.last_answered_question,
"entry_status" : this.entry_status
}
return returnJSON;
}
dbManager is this.adminInstance:
export class DatabaseManager{
private static adminInstance:any;
static getAdminInstance(): any {
if(!this.adminInstance)
admin.initializeApp(functions.config().firebase);
this.adminInstance = admin;
return this.adminInstance.firestore();
}
}
I am getting below error. How to solve it?
Error: Invalid use of type "undefined" as a Firestore argument.
at Object.exports.customObjectError.val [as customObjectError] (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/validate.js:164:14)
at Function.encodeValue (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/document.js:813:20)
at Function.encodeFields (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/document.js:683:36)
at Function.fromObject (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/document.js:223:55)
at WriteBatch.set (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/write-batch.js:301:39)
at DocumentReference.set (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/firestore/src/reference.js:420:8)
at testEntryService.createEntry (/user_code/services/test-entry-service.js:19:30)
at /user_code/services/intentService.js:22:36
at Function.<anonymous> (/user_code/node_modules/actions-on-google/dist/service/dialogflow/dialogflow.js:146:23)
at next (native)
Since I am new to Firebase, I am unable to identify this error. What is the root cause of the issue?

Replacing bluebird with node.js native promises breaks Promise.reject

The following code works perfectly fine when I use bluebird promises:
import * as Promise from 'bluebird';
getAccount(id) {
var account = find(accounts, ['id', id]);
return account ?
Promise.resolve(account) :
Promise.reject(new NotFoundError());
}
NotFoundError is defined as follows:
export function NotFoundError(message = 'Not Found') {
this.name = 'NotFoundError';
this.message = message;
this.stack = (new Error()).stack;
}
NotFoundError.prototype = Object.create(Error.prototype);
NotFoundError.prototype.constructor = NotFoundError;
However, if I remove the import of bluebird in getAccount() and let node.js take over promises, the code fails inside the NotFoundError() constructor because this is not defined. Specifically, the constructor is called twice, once correctly from the getAccount() code shown above and a second time by node.js's _tickCallback() function with this as undefined:
NotFoundError (errors.js:13)
runMicrotasksCallback (internal/proces…ext_tick.js:58)
_combinedTickCallback (internal/proces…ext_tick.js:67)
_tickCallback (internal/proces…ext_tick.js:98)
Why is node.js calling the NotFoundError() constructor a second time and that too incorrectly!!!
Please help.
The issue is caused by this line:
.catch(NotFoundError, function() { ... })
Native promises don't have an option to pass a specific error class to a catch method, so what happens is that when an error occurs, NotFoundError is called (without a new in front of it) because it's presumed to be the catch handler.

Resources