Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - File System - using a variable in fs.writeFile()

I'm terrible at explaining in words, so I'll show and explain whats happening and what I would like to have instead, as clearly as possible.


Current code in node.js: - This opens and overwrites a .json file, this works properly, so far so good.

fs.open(fileName, "r", function(err, fd) {
if(!err) {
    let file = require(fileName);
    if(!file.created) {
        file.created            = {};
        file.created.timestamp  = "123456789";

        let member_id = "456";

        file.member_id      = {};
        file.member_id.text = "hello!";
    }

    fs.writeFile(fileName, JSON.stringify(file, null, "\t"), function (err) {
        if(err) return console.log(err);
        console.log("added to " + fileName);
    });
    return;
}
else 
    return console.log("woops, something went wrong.....");

});


Content of .json file:

{
    "created": {
        "timestamp": "123456789"
    },
    "member_id": {
        "text": "hello!"
    }
}

So it's opening and overwriting the .json file properly. That's great. The problem with this is; it adds a key named "member_id", while I want it to be "456" (see example below, I've added a //comment with an <--- arrow pointing it out)


Content of how I would like the .json file to be:

{
    "created": {
        "timestamp": "123456789"
    },
    "456": {    // < ---------------------
        "text": "hello!"
    }
}

How can I make that possible? I cannot seem to figure it out at all...

like image 625
Roland Avatar asked Aug 11 '26 18:08

Roland


1 Answers

Change this:

file.member_id      = {};
file.member_id.text = "hello!";

to this:

 file[member_id]      = {};
 file[member_id].text = "hello!";

And, any other references to that same property.

When you want to use a variable name as a property name, you must refer to it with the bracket syntax. file.member_id just means to reference a property named member_id as you can see in your current result. Putting it in brackets as in file[member_id] tells the interpreter to get the contents of the member_id variable and use that as a property name.

like image 183
jfriend00 Avatar answered Aug 13 '26 09:08

jfriend00