【问题标题】:NodeJS not writing to file. Middleware not workingNodeJS 不写入文件。中间件不工作
【发布时间】:2017-10-16 06:35:42
【问题描述】:

我目前正在尝试让我的中间件在登录后将 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 查询将 usernamedate 写入文件:dbx.accounts.findOne(function(err, info)

为什么我的中间件没有按预期写入 json 文件?

编辑:

我将return 声明如下:

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

但它仍然没有写入文件。

【问题讨论】:

  • 在到达写入文件的代码之前,您正在从函数 return info 返回。
  • 是的,函数在 return 终止
  • 我应该把它放在哪里?我只是把它放在if 语句之后,它仍然不写。
  • 更新你的代码你最近尝试了什么
  • @ricky 我已经更新了我的问题。

标签: javascript json node.js express


【解决方案1】:

首先感谢有关此问题的所有帮助。在你们的大量帮助下,我弄清楚了哪里出了问题。

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

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

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2012-10-24
    • 2018-04-25
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    相关资源
    最近更新 更多