ana
ana

Reputation: 653

Not able to pass an object in writeFile method

I want to write into json file .I want to write an object that i am passing Here is the code

path.exists(logfile_name, function(exists) {
    if (!exists) {
         var jsonObject={ "req": req,
                     "result": result ,
                      "fields": fields } ;

            fs.writeFile(logfile_name ,jsonObject,function(err){
            if(err){
                console.log("error is: " + err)
            }
            else
                console.log("no error found");

             });
    }

});

In logfile_name it writes [object Object] But i want it to write like this { "req": value, "result": value , "fields": value}

Upvotes: 1

Views: 1507

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382130

If you don't pass a string or a buffer to writeFile, the toString function of what you pass is called. In your case it returns "[object Object]".

You have to convert it yourself :

fs.writeFile(logfile_name, JSON.stringify(jsonObject), function(err){

I would advise against naming a JavaScript object variable "jsonObject" : it might create confusion between what is an object and what is some JSON (i.e. a string holding the serialization of an object).

Upvotes: 4

Related Questions