discord.js client.off fails - node.js

I want to reload the code used for events in discord.js. The code is currently stored in a collection (the same way as commands in the discord.js guide). I have the following code:
client.events.delete(args[0]);
const file = require(`../events/${args[0]}.js`);
client.off(file.name, (...eventArgs) => this.events.get(file.name).run(this.client, this.shared, ...eventArgs));
message.reply(`Removed ${file.name} event.`);
The events are added to the listener using this:
for (const file of readdirSync('./events').filter(check => check.endsWith('.js'))) {
const event = require(`./events/${file}`);
this.shared.logger.log('info', `Loaded event ${event.name}`);
this.shared.events.set(event.name, event);
}
this.events.forEach(event => {
const file = require(`./events/${event.name}.js`);
this.client.on(file.name, (...eventArgs) => this.events.get(file.name).run(this.client, this.shared, ...eventArgs));
});
This runs without error, then when the event that was removed is triggered I get the following error in console:
TypeError: Cannot read property 'run' of undefined
at Client.<anonymous> (E:\Files\code\bot\index.js:85:73)
at Client.emit (events.js:315:20)
at WebSocketManager.debug (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:125:17)
at WebSocketShard.debug (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:168:18)
at WebSocketShard.sendHeartbeat (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:557:10)
at Timeout._onTimeout (E:\Files\code\bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:529:73)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7)
I assume this is caused because client.off isn't removing the event from the listener, but is deleting it from the collection, meaning that it is undefined when that event is triggered and the error is caused.

Discord event is always on. If you try to remove it, it will still persist until you've terminated the program, so you'd get the error. Try using this.client.once instead, and recall it when the desired event is needed.

Related

Json cannot read property of undefined

When I execute a command (the error doesn't occur when I type a normal message) in my discord bot I get an error saying:
Cannot read property 'active' of undefined
And it occurs when I try to console log an object from a json file where I store users data.
Those are the first lines of code of the index.js file of my bot, the line where I try to console log is where the error occurs
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require("fs");
const prefix = '>';
let xp = require("./storage/dbGeneral.json");
let pr = require("./storage/dbPremium.json");
let lv = require("./storage/levels.json");
client.on('message', message => {
console.log(pr[message.author.id].active);
}
This is the json file where I store the data
{
"397387465024864257": {
"active": false,
"dateStart": "",
"dateEnd": ""
}
}
This is the error:
index.js:14
console.log(pr[message.author.id].active);
^
TypeError: Cannot read property 'active' of undefined
at Client.client.on.message (index.js:14:39)
at emitOne (events.js:116:13)
at Client.emit (events.js:211:7)
at MessageCreateHandler.handle (\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (\node_modules\ws\lib\event-target.js:120:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)
I really don't know what is the cause of the error, all other json requests work fine with the same method.
The error is caused by trying to access a property of something not defined.
To fix your problem, you must check if the user exists in your database.
let user = pr[message.author.id];
if(user) console.log(user.active)

How to fix 'events.js :167 error Error: connect ECONNREFUSED 127.0.0.1:443' in Node.js when no other apps seems to be attempting to use the port?

I'm getting the error described below when running my node.js app after perfoming a few api calls.
The error does not always show in the exactly same place/line of code. But most of the times it is at the end of the api call.
events.js:167
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1113:14)
Emitted 'error' event at:
at TLSSocket.socketErrorListener (_http_client.js:391:9)
at TLSSocket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
Based on similar questions here at SO my hypothesis is that a) there is something using 127.0.0.1:443 and therefore conflicting with my app or b) node is trying to use 127.0.0.1:443 but there is nothing there for it to use (my app is listening to localhost :3000).
Hyphothesis a) doesn't seem likely since after running netstat -ano | findstr 127.0.0.1:443 nothing shows up (when app is running and right after it terminates).
Also killed every node.exe and mongod.exeb using any port in my computer, closed the terminal and restarted the node app without success.
In case error is related with hypothesis b) I'm not sure how to address it.
api.post('/parsePOpdf', wagner.invoke(function(Pdfeq, Pdfdocspec, Product, User, Order){
return async function(req,res){
//... some code
pdfParser.on("pdfParser_dataError", errData => console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", async function(pdfData) {
fs.writeFile("./test.json", JSON.stringify(pdfData), function(err){
console.log(err);
});
let pages = pdfData.formImage.Pages;
//console.log('pages 557', pages);
let order = {
orderDetails : {
supplier : [{
item : []
}]
}
};
for (const page of pages){
let value = await getItemsInPDF(page, productKeys, pdfParsingDetails, order, Product, customer, supplierLink, User);
//... more code
order = value;
}
return res.json(order);
});
pdfParser.loadPDF(pdfFile);
}
}));
I would expect the code to finish without throwing this error.
It turns out that the problem was in the api code: an http.get line to fetch a remote file was generating the conflict. This makes sense since the error was not present for other endpoints of the api.
So learning is that if the terminal reports no app using the suspected conflicting port (see question) answser should be within the same code and you need to go line by line to identify which one is causing the problem (instead of focusing on other apps trying to use the same port, like I was focusing on).

NodeJS : Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:111:27)

Using Polling like below to check if the content of the file is changed then, other two functions are called
var poll_max_date=AsyncPolling(function (end,err) { if(err) {
console.error(err); } var stmp_node_id=fs.readFileSync(path.join(__dirname,'node_id'),"utf8");
console.log("--------loaded node : "+stmp_node_id);
if(druid_stmp_node_id!=stmp_node_id) {
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// // DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire();
druid_stmp_node_id=stmp_node_id; }
end(); }, 1800000).run();//30 mins
Its working fine for sometime, but then getting below error like after 4 - 5hours :
events.js:167
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
tried using fs.watch to monitor the changes in the file instead of polling like below :
let md5Previous = null; let fsWait = false;
fs.watch(dataSourceLogFile, (event, filename) => { if (filename) {
if (fsWait) return;
fsWait = setTimeout(() => {
fsWait = false;
}, 1000);
const md5Current = md5(fs.readFileSync(dataSourceLogFile));
if (md5Current === md5Previous) {
return;
}
md5Previous = md5Current;
console.log(`${filename} file Changed`);
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire(); } });
Its is also working fine for sometime, but then getting same error like after 4 - 5hours :
events.js:167 throw er; // Unhandled 'error' event ^
Error: read ECONNRESET at TCP.onStreamRead
(internal/stream_base_commons.js:111:27) Emitted 'error' event at: at
emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT
(internal/streams/destroy.js:50:3)
But when run in Local Machine, its working fine. the error occurs only when run in remote Linux Machine.
somebody can help me how I can fix that problem?
Use fs.watchFile once , because fs.watch is not consistent across platforms,
https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener
Change your code according to the requirement.
It has been happening since the users are closing the browser before the data request is received, leading to Connection Reset.
Used PM2 (http://pm2.keymetrics.io/) to run the application, and it is working great now .

Cannot find module '../dialog' (Electron fatal error)

In electron, I encounter the following error:
module.js:440
throw err;
^
Error: Cannot find module '../dialog'
at Module._resolveFilename (module.js:438:15)
at Function.Module._resolveFilename (/opt/App/resources/electron.asar/common/reset-search-paths.js:47:12)
at Function.Module._load (module.js:386:25)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at Object.get [as dialog] (/opt/App/resources/electron.asar/browser/api/exports/electron.js:35:14)
at process.<anonymous> (/opt/App/resources/electron.asar/browser/init.js:64:31)
at emitOne (events.js:96:13)
at process.emit (events.js:188:7)
at process._fatalException (node.js:276:26)
It happens on a child process spawn that fails in Linux. Strange because I do have a try catch block around that, yet it still results in an uncaughtexception, as seen in the code in browser/init.js from electron.asar:
// Don't quit on fatal error.
process.on('uncaughtException', function (error) {
// Do nothing if the user has a custom uncaught exception handler.
var dialog, message, ref, stack
if (process.listeners('uncaughtException').length > 1) {
return
}
// Show error in GUI.
dialog = require('electron').dialog
stack = (ref = error.stack) != null ? ref : error.name + ': ' + error.message
message = 'Uncaught Exception:\n' + stack
dialog.showErrorBox('A JavaScript error occurred in the main process', message)
}
As said, my code is in a try catch:
try {
server = childProcess.spawn(java, ["-jar", "App.jar"], {
"cwd": serverDirectory,
"detached": true
}, function(err) {
console.log("in callback");
});
} catch (err) {
console.log("here we are");
console.log(err);
}
But neither the callback nor the catch block is reached. Any ideas what is going on here and why the default dialog module cannot be found?
I found same error with electron 1.6.2
Figured it was due, when closing the application an error occur and electron want to display it in a dialog, maybe the close process has started and electron can't load this module, anyway I add:
const { dialog } = require('electron');
in main.js, no more error in console instead a dialog the error, I can fix it, After that I let the require just in case.
I hope I understand your question correctly...
If by "default dialog module", you mean the electron dialog API, then you can require that like so: const { dialog } = require('electron'). (Or in pre-1.0 versions simply require('dialog'). See https://github.com/electron/electron/blob/master/docs/api/dialog.md
Also the try/catch needs to be around the require in the child process. The try/catch you have is around the spawning of the child process in the parent. That require is failing in an entirely different node.js process, so it's not caught in the parent process that spawned it. It sounds like your child process code might work better if it looked like:
try {
const dialog = require('dialog');
} catch(e) {}
Also, if childProcess.spawn is referring to the core node module child_process, that doesn't accept a callback function. See https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
Can you share the code from your child process? That might help more.

ForEachLine() in node.js

Referring to slide no 35 in ppt on slideshare
When I run this code
var server = my_http.createServer();
server.on("request", function(request,response){
var chunks = [];
output = fs.createWriteStream("./output");
request.on("data",function(chunk){
chunks = forEachLine(chunks.concat(chunk),function(line){
output.write(parseInt(line,10)*2);
output.write("\n");
})
});
request.on("end",function(){
response.writeHeader(200,{"Content-Type":"plain/text"})
response.end("OK\n");
output.end()
server.close()
})
});
server.listen("8080");
I get error as
chunks = forEachLine(chunks.concat(chunk),function(line){
^
ReferenceError: forEachLine is not defined
Of course I unserstand that I need to include some library but when I googled this I found nothing . Since I am complete newbie to this I have absolutely no idea how to resolve it.
Any suggestions will be appreciable.
EDIT
Using the suggested answer I am getting error as
events.js:72
throw er; // Unhandled 'error' event
^
TypeError: Invalid non-string/buffer chunk
at validChunk (_stream_writable.js:150:14)
at WriteStream.Writable.write (_stream_writable.js:179:12)
at /var/www/html/experimentation/nodejs/first.js:18:20
at Array.forEach (native)
at forEachLine (/var/www/html/experimentation/nodejs/first.js:8:60)
at IncomingMessage.<anonymous> (/var/www/html/experimentation/nodejs/first.js:17:18)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:736:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
Thanks
See proxy_stream.js
function forEachLine(chunks, callback) {
var buffer = chunks.join("")
buffer.substr(0, buffer.lastIndexOf("\n")).split("\n").forEach(callback)
return buffer.substr(buffer.lastIndexOf("\n") + 1).split("\n")
}
The link to the repo was on the first slide.
EDIT BY LET's CODE FOR ERROR MESSAGE
Came to know the actual issue now .
I was using nod v0.10 and it is buggy in getting the streams so I was getting the error. Downgraded to v0.8 and same code is working perfect .

Resources