简体   繁体   English

在 node.js 中的文件中保存和删除行

[英]Saving and deleting lines to & from file in node.js

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 UserToBan1 Banned-By Reason-For-Ban

UserToBan2 Banned-By Reason-For-Ban UserToBan2 Banned-By Reason-For-Ban

UserToBan3 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.我是 node.js 和 javascript 的新手,但我不知道什么是最好的方法。 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.我创建了一个 banlist.json 文件,我知道如何打开和关闭该文件,但添加、删除行并检查第一个变量是我卡住的地方。

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).编辑:这是我现在正在使用的代码,但是当我使用 console.log(data) 或 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 ------------------------------------------------------------

If you know how to read/write a file, you can directly use store the data as JSON in that file, eg:如果您知道如何读/写文件,则可以直接使用将数据作为 JSON 存储在该文件中,例如:

{
      "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:读取文件时,将文件内容解析为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")
            }
        })
    }   
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM