0

I am currently trying to make my middeware write json data to a file after is logged in. My issue is that whenever I execute the function, nothing gets written to the file nor output in the console.

I've used this question as an example Example 1 but still nothing works.

Here is the middleware part of my NodeJS script:

function isLoggedIn(req, res, next) {
    dbx.accounts.findOne(function(err, info){
        console.log(JSON.stringify(info.username));
        return info;

        var xx = info.username;
        var date = new Date();
        console.log(JSON.stringify(date));
        var obj = {
           users: []
        };

        fs.readFile('logs.json', 'utf8', function readFileCallback(err, data){

        console.log(JSON.stringify(obj));
        obj.users.push({time: date, name: xx});
            if (err){
                console.log(err);
            } else {
            obj = JSON.parse(   ); //now it an object
            obj.users.push({time: date, name: xx}); //add some data
            json = JSON.stringify(obj); //convert it back to json
            fs.writeFileSync('logs.json', json, 'utf8', JSON.stringify(output)); // write it back 
        }});

    });


    //logs.stamps.push({id:----, timestamp:date.toString()})

    console.log('here is Authenticated', req.isAuthenticated()) //prints out 'here is Authenticated' if the Passport login is successful
    if (req.isAuthenticated()){
        return next();
    }else{
        console.log("routes Print log You Cannot Log in!");
    }
}

I am trying to write username and date to the file by querying it with Mongo first: dbx.accounts.findOne(function(err, info)

Why is my middleware not writing to the json file as supposed?

EDIT:

I've put the return statement like this:

fs.readFile('logs.json', 'utf8', function readFileCallback(err, data){

console.log(JSON.stringify(obj));
obj.users.push({time: date, name: xx});
    if (err){
        console.log(err);
    } else {
    obj = JSON.parse(   ); //now it an object
    obj.users.push({time: date, name: xx}); //add some data
    json = JSON.stringify(obj); //convert it back to json
    return info; 
    fs.writeFileSync('logs.json', json, 'utf8', JSON.stringify(output)); // write it back 
}});

but it still doesn't write to the file.

ric
  • 627
  • 1
  • 12
  • 23
ZombieChowder
  • 1,187
  • 12
  • 36

1 Answers1

0

First of all thanks for all the help regarding this questions. I figured out what was wrong with quite a lot of help from you guys.

I completely removed the return info statement since I didn't really need it. Secondly I removed the obj = JSON.parse(obj) because it's already being parsed by the javascript interpreter. I also removed the JSON.stringify(output) because I'm not using the output anywhere.

Thanks for the help and sorry if I caused any confusion.

ZombieChowder
  • 1,187
  • 12
  • 36