繁体   English   中英

NodeJS未写入文件。 中间件不起作用

[英]NodeJS not writing to file. Middleware not working

我当前正在尝试使我的中间件在登录后将json数据写入文件。我的问题是,每当我执行该函数时 ,都不会写入文件或在控制台中输出任何内容。

我以这个问题为例例子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(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 
}});

但它仍然不会写入文件。

首先,感谢您对此问题的所有帮助。 我发现你们提供了很多帮助,出了什么问题。

由于我确实不需要return info声明,因此我将其完全删除。 其次,我删除了obj = JSON.parse(obj)因为javascript解释器已经对其进行了解析 我还删除了JSON.stringify(output),因为我没有在任何地方使用输出。

感谢您的帮助,如果造成任何混乱,我们深表歉意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM