0

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 ------------------------------------------------------------
  • The `fs.readFile(file, function(content) ` should read `fs.readFile(file, function(err, content) `. I already fixed my answer below accordingly – mottek Sep 29 '20 at 07:52
  • var transformed_content = JSON.dumps(data); produces an error, TypeError: JSON.dumps is not a function. At least it got past the first hurdle :) I am trying to understand how it works so that bug fixing will be easier. – Charly Willy Sep 29 '20 at 08:36
  • ok i managed to get it working by changing the line var transformed_content = JSON.dumps(data); to var transformed_content = JSON.stringify(data); There is only one simple problem now, it doesnt save as the same nice format and just saves everything on the same line. – Charly Willy Sep 29 '20 at 16:16
  • 1
    Try `JSON.stringify(data, null, 4)`. See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify – mottek Sep 29 '20 at 19:58
  • heh, that worked perfectly! I have been working on this all day trying everything I could find, nothing worked. I even tried JSON.dumps(data, indent=4, sort_keys=true); but failed. Tips hat to you mottek and thank you kindly – Charly Willy Sep 29 '20 at 20:11

1 Answers1

3

If you know how to read/write a file, you can directly use store the data as JSON in that file, e.g.:

{
      "UserToBan1": {
          "bannedby": "user who banned UserToBan1",
          "reason": "reason for the ban"
      },
      "UserToBan2": {
          "bannedby": "user who banned UserToBan2",
          "reason": "reason for the ban"
      },
      "UserToBan3": {
          "bannedby": "user who banned UserToBan3",
          "reason": "reason for the ban"
      }
}

When reading the file, parse the file content as JSON:

fs = require('fs');
var file = "/path/to/json/file";
fs.readFile(file, function(err, content) {
    if (err) {
        console.log("Error reading file: " + (err.stack || err))
    } else {
        var data = JSON.parse(content);
        console.log(Object.keys(data));
        // Delete line (see: https://stackoverflow.com/questions/3455405/how-do-i-remove-a-key-from-a-javascript-object/28797751)
        // example to delete user from list
        delete data["UserToBan1"]
        // example to add user to list
        data["UserToBan4"] = {
            "bannedby": "user who banned UserToBan4",
            "reason": "reason for banning UserToBan4"
        }
        console.log(Object.keys(data));
        // Convert JSON object to string
        var transformed_content = JSON.stringify(data, null, 4);
        // 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")
            }
        })
    }   
});
mottek
  • 929
  • 5
  • 12
  • I know how to open and close files but not reading from or writing to files. – Charly Willy Sep 28 '20 at 20:17
  • 1
    I edited my answer to contain the code to save the data – mottek Sep 28 '20 at 20:23
  • thanks, I was expecting links to suggestions on its best approach but you have saved me a lot of time. much appreciated – Charly Willy Sep 28 '20 at 20:30
  • C:\xampp\server\index.js:60 console.log(Object.keys(data)); ^ TypeError: Cannot convert undefined or null to object at Function.keys () at C:\xampp\server\index.js:60:24 at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3) PS C:\xampp\server> – Charly Willy Sep 28 '20 at 21:29
  • What is the output of `console.log(data);` if you put it directly before `console.log(Object.keys(data))` – mottek Sep 28 '20 at 21:41
  • How can I add people to this list? It deletes fine but I can not find a way to add anything – Charly Willy Sep 30 '20 at 19:59