arvind
arvind

Reputation: 788

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,

var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
    "try" : "till success"
}
];

jsonContent.push(data);

fs.writeFileSync(filename,jsonContent);

I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that? The correct format i am looking for is ,

[
    user1-details : {
         //user1 details
    },

    user2-deatils  : {

    }//So on
]

Upvotes: 0

Views: 168

Answers (1)

Shanoor
Shanoor

Reputation: 13662

Object has no push function, arrays do. Your json is invalid too, it should be an array:

[ // here
    {
         //user1 details
    },

    {
         //So on
    }
] // and here

Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:

var data = {
    "try" : "till success"
};

You also have to stringify the object before writing it back to the file:

fs.writeFileSync(filename, JSON.stringify(jsonContent));

You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Upvotes: 2

Related Questions