NodeJS crashes after sometime of leading a csv file - javascript

I've been working on a project that outputs xml upon reading a csv, I use the fs.createReadStream() method to read the csv file but after some time, the terminal just crashes.
And I get
C:\Users\username\Documents\Programming\Node Projects\DAE Parser\main.js:13
row["Value"].includes("tri") ||
^
TypeError: Cannot read property 'includes' of undefined
It doesn't read the whole file.
here's what i'm doing
fs.createReadStream("test.csv")
.pipe(csv())
.on("data", row => {
if (
row["Value"].includes("tri") ||
row["Value"].includes("vt") ||
row["Value"].includes("vx") ||
row["Value"].includes("vn")
) {
console.log(row)
}
})

Your row["Value"] is undefined, you can add a condition to check if it's falsy
fs.createReadStream("test.csv")
.pipe(csv())
.on("data", row => {
if (row["Value"] && (
row["Value"].includes("tri") ||
row["Value"].includes("vt") ||
row["Value"].includes("vx") ||
row["Value"].includes("vn")
)) {
console.log(row)
}
})

Your code is vulnerable in cases where:
row is not an object
row["Value"] does not exist or is not an array.
If you want to be completely safe against these in any particular row, then you can do this:
fs.createReadStream("test.csv")
.pipe(csv())
.on("data", row => {
if (typeof row === "object") {
let arr = row.Value;
if (arr && Array.isArray(arr) && (
arr.includes("tri") ||
arr.includes("vt") ||
arr.includes("vx") ||
arr.includes("vn")
)) {
console.log(row);
}
}
})

Related

Check for multiple cases without if statement in JavaScript

I created this function which should check for every case, and if one of the case not corresponding then i should get immediately the result.
const addText = (data, addAlternative) => {
return (data !== 'N/T' || data === 0 || data) ? data : addAlternative;
};
console.log(addText('N/T', 'alternative'))
in my case addText('N/T', 'alternative') i get N/T, but i expect to get alternative word as a result. How to change my statement to check every situation and if one of the situation occurs i have to get the right answer like in the example that i provided?
You are receiving NT as output, because you are checking the truthy status of data parameter isiide the function by using data !== 'N/T' || data === 0 || data.
Update that to data !== 'N/T' || data === 0, it will work as expected.
const addDefaultTextIfIsEmpty = (data, addAlternative) => {
return (data !== 'N/T' || data === 0) ? data : addAlternative;
};
console.log(addDefaultTextIfIsEmpty('N/T', 'alternative'))
If you want to output data if the param is not defined, just check !data inside the condition, there you dont need to add data === 0 because !data will handle null, undefined, empty, and zero checks
const addDefaultTextIfIsEmpty = (data, addAlternative) => {
return (data !== 'N/T' || !data) ? data : addAlternative;
};
console.log(addDefaultTextIfIsEmpty('N/T', 'alternative'))
You need to prevent if (data) from being tested if data is 'N/T' but currently it is being evaluated at the end because of short-circuiting.
Your logic is basically:
return (false || false || true) ? ...
^ ^ \____ because data contains 'N/T'
| |
| '-------- data is not 0
because data is N/T
This obviously resolves to true because the || operator only needs one of the expressions to be true.
What you actually want is:
return (data !== 'N/T' && (data === 0 || data)) ? ...
^
|
remember De-Morgan's Theorem
(google it if you don't know)
const addText = (data, addAlternative) => {
return (data !== 'N/T' || data === 0) ? data : addAlternative;
};
const addText = (data, addAlternative) => {
return ((data && data !== 'N/T') || data === 0) ? data : addAlternative;
};
console.log(addText('N/T', 'alternative'))
/* Try below */
const addDefaultTextIfIsEmpty = (data, addAlternative) => {
return (data !== 'N/T' || data === 0) ? data : addAlternative;
};
addDefaultTextIfIsEmpty('N/T', 'alternative')
You are using data in if statement and you are passing 'N/T' which changes the value to false and according to the logic the value always be true. Try this solution.
const addText = (data, addAlternative) => (data && (data !== 'N/T' || data === null || data === 0)) ? data : addAlternative;
console.log(addText('N/T', 'alternative'))

Can't read property 'name' of undefined

I've been getting an error along the lines of "Cannot read property 'name' of undefined" and the error traces back to this code
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
What's going wrong here?
slightly larger peice of code
if (!message.member.hasPermission('MANAGE_ROLES')) return message.channel.send(`You do not have MANAGE_ROLES permission`)
try {
const user = message.mentions.users.first();
const member = message.guild.member(user);
const roleName = message.guild.roles.cache.find(r => (r.name === args[1].toString()) || (r.id === args[1].toString().replace(/[^\w\s]/gi, '')));
//after this i create a discord embed, give the member the role specified then send the embed.
} catch (err) {
console.log(err)
}
Add an Elvis operator:
const roleName = message.guild.roles.cache.find(r =>
(r?.name === args[1].toString())
|| (r?.id === args[1].toString().replace(/[^\w\s]/gi, ''))
);
Or do it the old way:
const roleName = message.guild.roles.cache.find(r =>
r
&& (r.name === args[1].toString())
|| (r.id === args[1].toString().replace(/[^\w\s]/gi, ''))
);
So you're getting this error because you're trying to access 'r.name' in your Array.find() method and some of the entries in the array appear to be 'undefined' or 'null'. I would first run an Array.filter(r => !!r) and then chain on the .find() method afterwards to make sure all your entries are not undefined/null.

how to fix this TypeError: Cannot read property 'name' of null

how to fix this error
music.on('voiceStateUpdate',(lama, baru) => {
var state = null;
let Role = baru.roles.find((r) => ["IRON", "BRONZE"].includes(r.name));
const kategorikanal = '700743802574602260'
const channelid = '700743824346972231'
if(!lama.voiceChannel && !baru.voiceChannel) return;
if(!lama.voiceChannel && baru.voiceChannel) {state = "join"}
else if(lama.voiceChannel && !baru.voiceChannel) {state = "leave"}
else if(lama.voiceChannel.id !== baru.voiceChannel.id) {state = "move"}
else if(lama.voiceChannel.id == baru.voiceChannel.id) return;
console.log(state);
//!baru.member.roles.has(allowedRole)
if(baru.voiceChannelID === channelid || !baru.voiceChannelID === Role || Role !== null && Role !== '') {
console.log(baru.displayName + ' gabisabgo hrus ada rank ranked ');
// const Role = baru.guild.roles.get("724997095236304987");
baru.guild
.createChannel(`${Role.name} | ${baru.user.username}`,"voice")
.then(tempChannel => {
tempChannel.overwritePermissions(baru.guild.defaultRole.id, {
CONNECT: false,
})
tempChannel.overwritePermissions(Role.id, {
CONNECT: true
})
tempChannel.setParent(kategorikanal);
baru.setVoiceChannel(tempChannel.id);
tempChannel.setUserLimit("5");
})
.catch(console.error)
}
if(lama.voiceChannelID || !lama.voiceChannelID === Role || Role !== null && Role !== '') {
console.log(lama.displayName + ' gabisabgo hrus ada rank ranked ');
const voicelama = lama.guild.channels.get(lama.voiceChannelID);
let Role = baru.roles.find((r) => ["IRON", "BRONZE"].includes(r.name));
if(voicelama.name.startsWith(`${Role.name} | ${baru.user.username}`)){
let sawadikap = `**${baru.user.username}'s**` + " **Team**"
var koko = new Discord.RichEmbed()
.setColor("#FF4654")
.setThumbnail(`${baru.user.avatarURL}`)
.addField('**Good Game Well Played**',`${sawadikap}`)
.setFooter("#Valorant Indonesia Community." , 'https://i.imgur.com/yPWqxxu.png')
voicelama.delete()
.then(function() {
music.channels.get('725080861392896101').send(koko)
})
.catch(console.error);
}
}
})
ERROR VIEW
.createChannel(${Role.name} | ${baru.user.username},"voice")
^ TypeError: Cannot read property 'name' of null
Have you stepped through the code in debug mode? I recommend setting breakpoints, creating watches, and checking the value of the variables as you step through. If you don't feel comfortable doing so, can you please put in the following, and tell me what the console logs? :
console.log(Role)
console.log(Role.name)
Although Role is not null, The value of Role.name is null, meaning that it has no value assigned to it. That issue occurs here:
let Role = baru.roles.find((r) => ["IRON", "BRONZE"].includes(r.name));
So I see two possibilities:
No roles contain those names.
I thought that find should only result one result, but I can't seem to find good documentation of that method. Is it possible that both roles are found and a collection is returned? This would mean that there would be a collection of multiple roles, meaning that Role would not contain the data members that a Role object type would. This means that you would have to index one of the roles before using the name.
//
//if there isn't a matching role, then terminate the method.
if (Role == null)
{
return;
}
//if there are multiple roles that match the criterion, just use the first one.
//The alternative is that we could make it into a loop that handles it for all of them.
else if (Role instanceof Array)
{
if (Role.length == 0)
{
return;
}
Role = Role[0]
}
Add the above lines before calling baru.guild.createChannel.

JS Array.find if undefined element

I try to merge two arrays:
productsAll = parserArrayFull.map((item) => {
return {
...item,
...firestoreArrayFull.find((y) => y.productSKU === item.SELLER_SKU),
};
});
Everything works OK if in "firestoreArrayFull" there is "productSKU" with the same value like item.SELLER_SKU. But if not there is error
"Cannot read property 'productSKU' of undefined"
How to make condition for this situation? I would like to keep "item" only in the case of error.
regards
Looks like you have some null values in firestoreArrayFull array.
Try put y && before you make a comparison to make sure y isn't null or undefined.
productsAll = parserArrayFull.map((item) => {
return {
...item,
...firestoreArrayFull.find((y) => y && y.productSKU === item.SELLER_SKU),
};
});
Update
If not found, adds productSKU property equals to item.SELLER_SKU.
productsAll = parserArrayFull.map((item) => {
return {
...item,
...(firestoreArrayFull.find((y) => y && y.productSKU === item.SELLER_SKU) || { productSKU: item.SELLER_SKU }),
};
});

Uncaught TypeError: Cannot read property 'get' of null in map function

I have findPlayerWithID function which return matched player id
function findPlayerWithID(players, id) {
let i = 0;
for (; i < players.count(); i++) {
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
if (players.map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
}
return -1;
}
But sometimes it give error in this line
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
error is
gameStore.js:38 Uncaught TypeError: Cannot read property 'get' of null
at gameStore.js:38
at immutable.js:3018
at Ue.__iterate (immutable.js:2208)
at r.__iterateUncached (immutable.js:3017)
at F (immutable.js:606)
at r.T.__iterate (immutable.js:322)
at r.toArray (immutable.js:4260)
at new Ue (immutable.js:2067)
at _t (immutable.js:3572)
at Ue.map (immutable.js:4403)
I think error because of null object
How can I check null in this line
if (players.map((degisken) => degisken.get('id')).
immutable.js:1317 Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
Updated
with #canaan-seaton answear I change
this
if (players.filter(degisken => degisken !== null).map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
this work
but it give another error in immutablejs
Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
at this line in immutablejs
function(m ) {return typeof m.merge === 'function' ?
I searcg for that error
there is some info but I don't understand what should I do https://github.com/facebook/immutable-js/issues/597
here is my console
Generally , it is not a good practice to check for equality to undefined.
I would try to do it this way:
First of all, to make sure that degisken does exists you can go with degisken && degisken.get(id)
Second, you might want to use Object's hasOwnProperty method, which will be useful in here:
players.map((degisken) => {
const id = degisken && degisken.get('id');
if(id && id.hasOwnProperty('_tail') && id._tail.array[i] === id){
return i
}
});
if you just want to check if the array has elements then you can do something like the following....
if (players && players.length > 0) {/* Do Stuff */}
if you are concerned with specific indices within the array being null then you could do something like this....
if (players.filter(degisken => degisken !== null)
.map((degisken) => degisken.get('id'))._tail === undefined)
{/* Do Stuff */}

Categories

Resources