Json cannot read property of undefined - node.js

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)

Related

discord.js client.off fails

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.

How to parse error parameter in request callback?

I'm deliberately triggering an error in a stored procedure under certain conditions which I want to catch in my Node.js API which uses the Tedious package.
Code Snippet from API:
let request = new Request(sql, (err)=>{
if (err) {
sqlerr = err;
console.log(typeof(err));
console.log("**RQ-ERROR**", err);
}
});
In the callback of the "Request" object above there is an "err" parameter. The "typeof()" returns "object"; however, when I dump it to the console it looks like this:
**RQ-ERROR** { RequestError: Duplicate entry for specified period
at RequestError (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\errors.js:32:12)
at Parser.tokenStreamParser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\connection.js:723:34)
at emitOne (events.js:96:13)
at Parser.emit (events.js:188:7)
at Parser.parser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
at emitOne (events.js:96:13)
at Parser.emit (events.js:188:7)
at addChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:297:12)
at readableAddChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:279:11)
at Parser.Readable.push (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:240:10)
message: 'Duplicate entry for specified period',
code: 'EREQUEST',
number: 50000,
state: 1,
class: 16,
serverName: 'PERSODG2LNN52\\SQLEXPRESS',
procName: 'CreateStatusReport',
lineNumber: 44 }
This almost looks like a JavaScript object but, as you can see, the "RequestError" data isn't quoted nor is there a comma after the text "240:10)" just before the "message" member. I'm not sure if this is a bug in TDS or if I'm just missing something but I cannot access any of the members as it is. I'd have to convert it to a string and parse it which is fine but isn't very elegant.
Suggestions?
as you can see, the "RequestError" data isn't quoted nor is there a comma after the text "240:10)"
These are artifacts of the console logging out the error message. You can try it out for yourself with something like the following:
$ node
> console.log(new Error('this is an error object!'));
Error: this is an error object!
at repl:1:13
at Script.runInThisContext (vm.js:119:20)
at REPLServer.defaultEval (repl.js:332:29)
at bound (domain.js:395:14)
at REPLServer.runBound [as eval] (domain.js:408:12)
at REPLServer.onLine (repl.js:639:10)
at REPLServer.emit (events.js:194:15)
at REPLServer.EventEmitter.emit (domain.js:441:20)
at REPLServer.Interface._onLine (readline.js:290:10)
at REPLServer.Interface._line (readline.js:638:8)
I'm not exactly sure what the desired outcome of this question is, but try inspecting the err.message property rather than using the typeof operator.

gcloud error: ApiError: Not Found at new util.ApiError

Anyone familiar with this gcloud exception:
ApiError: Not Found at new util.ApiError
(/site/node_modules/gcloud/lib/common/util.js:128:10) at
Object.parseHttpRespBody
(/site/node_modules/gcloud/lib/common/util.js:206:30) at
Object.handleResp
(/site/node_modules/gcloud/lib/common/util.js:146:18) at
/site/node_modules/gcloud/lib/common/util.js:447:12 at
Request.onResponse [as _callback]
(/site/node_modules/gcloud/node_modules/retry-request/index.js:120:7)
at Request.self.callback
(/site/node_modules/request/request.js:187:22) at Request.emit
(events.js:98:17) at Request.
(/site/node_modules/request/request.js:1044:10) at Request.emit
(events.js:95:17) at IncomingMessage.
(/site/node_modules/request/request.js:965:12) at IncomingMessage.emit
(events.js:117:20) at _stream_readable.js:944:16 at
process._tickDomainCallback (node.js:492:13)
It appears only in production (of course) and currently consistently. It used to appear periodically and the assumption was that it is a glitch # gCloud since locally it could not be reproduced. It is related to the part of the code which uses the simplest gCloud lib method bucket.upload with no parameters other than the file ... Here is the current function which does it:
function uploadToGoogleCloud(filePath, makePublic) {
var gstorage = gcloud.storage({
projectId: EXAMPLE_projectId,
credentials: EXAMPLE_credentials,
});
var spBucket = Promise.promisifyAll(gstorage.bucket(EXAMPLE_bucket));
return spBucket.uploadAsync(filePath).then(function(file) {
if (makePublic) {
var fileAsync = Promise.promisifyAll(file);
return fileAsync.makePublicAsync().then(function() {
return file;
});
}
return file;
});
}
Any feedback is greatly appreciated.
The error is a bit obscure, but was correct for me. I got this error when I in some cases were trying to write to a bigquery table that did not exist (I accidentally passed "undefined" as the tablename), I suspect that there is some 404 error coercion going on under the hood.

Sending bitcoins using bitcoinjs-lib

I'm following tutorial for bitcoinjs at https://medium.com/#orweinberger/how-to-create-a-raw-transaction-using-bitcoinjs-lib-1347a502a3a#.wkf9g2lk0
I receive undefined error for
var key = bitcoin.ECKey.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");
Reading https://github.com/bitcoinjs/bitcoinjs-lib/issues/487 I use instead
var key = bitcoin.ECPair.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");
For line : console.log(key.pub.getAddress().toString()); (from tutorial)
I receive similar exception :
TypeError: Cannot read property 'getAddress' of undefined
at repl:1:20
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
at REPLServer.Interface._ttyWrite (readline.js:827:14)
'getAddress' method is also deprecated, what to use instead ?
Any other tutorials for sending bitcoins ? They seem difficult to find ?
This should work
var key = bitcoin.ECPair.fromWIF("L1Kzcyy88LyckShYdvoLFg1FYpB5ce1JmTYtieHrhkN65GhVoq73");
var address = key.getAddress().toString()
console.log(address) // 17hFoVScNKVDfDTT6vVhjYwvCu6iDEiXC4
Better still using newer version of bitcoin.js library do
const bitcoin = require('bitcoinjs-lib');
let keyPair = bitcoin.ECPair.makeRandom();
let publicKey = keyPair.publicKey
const { address } = bitcoin.payments.p2pkh({ pubkey: publicKey });
const privateKey = keyPair.toWIF();
console.log(address)
console.log(privateKey)

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