I have written code for a chatroom, I am trying to implement a ban list which bans by username. In the file I want it to look something like this (without the blank lines between each other)..
UserToBan1 Banned-By Reason-For-Ban
UserToBan2 Banned-By Reason-For-Ban
UserToBan3 Banned-By Reason-For-Ban
I want to be able to check if the person is listed in that file by username. Want to be able to remove the line from the list (unban) and to be able to add someone to the file. I am new to node.js and javascript but I don't know what would be the best way to do this. I have created a banlist.json file which I know how to open and close but adding, removing lines and checking the first variable is where I am stuck.
EDIT: This the code I am now working with but seems to produce a null value when I console.log(data) or console.log(content).
s.on('connection', function(ws) {
ws.on('message', function(message){
// START only on connection
message = JSON.parse(message);
if(message.type == "name"){
// start check for double login
var ConnectingUser = message.data;
var found = 0;
s.clients.forEach(function e(client) {
var ConnectedUser = client.personName;
if(ConnectedUser == ConnectingUser) {
client.send(JSON.stringify(
{
name: "Server",
data: "***We do not allow double logins!"
}
));
client.send(JSON.stringify(
{
name: "Server",
data: " Disconnected..."
}
));
client.close();
}
});
// end check for double login
console.log("Client <"+message.data+"> Connected");
memberJoinedChatMsg(ws, message);
ws.personName = message.data;
return;
}
// -- test stuff start ------------------------------------------------------------
var file = './banlist/banned.json';
fs = require('fs');
fs.readFile(file, function(content) {
var data = JSON.parse(content);
console.log(Object.keys(data));
// Delete line
delete data["UserToBan1"]
console.log(Object.keys(data));
// Convert JSON object to string
var transformed_content = JSON.dumps(data);
// write file here
fs.writeFile(file, transformed_content, function(err) {
if (err) {
console.log("Error writing file: " + (err.stack || err))
} else {
console.log("Saved file")
}
})
});
// -- test stuff end ------------------------------------------------------------