NodeJS没有写入文件。中间件无法正常工作

时间:2017-10-16 06:35:42

标签: javascript json node.js express

我目前正在尝试让我的middeware在登录后将json数据写入文件。我的问题是每当我执行函数时,没有任何内容写入文件,也没有输出到控制台

我已将此问题用作示例Example 1 但仍然没有任何作用。

以下是 NodeJS 脚本的中间件部分:

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!");
    }
}

我正在尝试通过首先使用Mongo查询用户名日期dbx.accounts.findOne(function(err, info)

  

为什么我的中间件没有按照假设写入json文件?

编辑:

我已经按照return这样的陈述:

fs.readFile(' logs.json',' utf8',函数readFileCallback(错误,数据){

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 
}});

但它仍然没有写入文件。

1 个答案:

答案 0 :(得分:0)

首先感谢有关此问题的所有帮助。我发现你们的帮助很多,这是错的。

我完全删除了return info声明,因为我并不真正需要它。 其次,我删除了obj = JSON.parse(obj),因为它已经被 javascript解释器解析了。我还删除了 JSON.stringify(输出),因为我没有在任何地方使用输出。

感谢您的帮助,对不起,如果我引起任何混淆。

相关问题