node.jsfilesyntax-erroroverwritenode.js-fs

why can't I overwrite file (fs node.js)?


I want to create a config file before specific actions. So this means I created a config file in my folder, at first containing nothing.

Then I run following code:

db.getData(function(err,data) { //it's an dynamodb don't know if this matter
    var entry = {
        dataItems: data.Items[0].items,
        timestamp: data.LastEvaluatedKey.timestamp.N
    };

    try {
        fs.writeFile("./config", JSON.stringify(entry), function (err) {
            if(err) {
                throw new Error(err);
            }
            callback(); //want to know when file is filled with data
        });

    } catch (err) {
        throw err;
    }
});

The file has content now. But I don't want to clear the file every time before this function get executed, it should be overwritten. If I run this code again I get an error message:

function (exports, require, module, __filename, __dirname) { {"data":{"S":"[{\
                                                                      ^^^^^^
SyntaxError: Unexpected token :

So the object is the response from my db which the code wrote in the file before. I cleared to file to test if this is a problem from the attempt to overwrite and run the code again and everything was fine again.

I was making researches what could be my problem, but the only thing I found was posts from people try to avoiding overwrite their files, so I guess I make a mistake by writing this file cause overwriting seems to be standard and not a special task to do. And this website shows how to use fs.writeFile and I can't see a difference to mine:


Solution

  • I've mocked the db.getData function to return valid data and it is working.

    var fs = require('fs');
    
    var db = {
      getData: function(callback) {
        var data = {"Items": [{"items": "entry"}], "LastEvaluatedKey": {"timestamp": {"N": 12323234}}};
        callback(null, data);
      }
    }
    
    var callback = () => console.log("It worked");
    
    db.getData(function(err,data) { //it's an dynamodb don't know if this matter
        var entry = {
          dataItems: data.Items[0].items,
          timestamp: data.LastEvaluatedKey.timestamp.N
        };
    
      try {
          fs.writeFile("./config", JSON.stringify(entry), function (err) {
              if(err) {
                  throw new Error(err);
              }
              callback(); //want to know when file is filled with data
          });
    
      } catch (err) {
          throw err;
      }
    });
    

    It seems that maybe your data can't be serialized correct? That would also explain what the interpreter is complaining about with Unexpected token :