Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将当前登录的用户追加到JSON文件_Javascript_Json_Node.js_Express_Fs - Fatal编程技术网

Javascript 将当前登录的用户追加到JSON文件

Javascript 将当前登录的用户追加到JSON文件,javascript,json,node.js,express,fs,Javascript,Json,Node.js,Express,Fs,我试图找到一种方法来获取当前登录的用户,然后将其附加到JSON文件中。下面是我的代码,首先读取目录,然后获取最新的文件,返回它,然后附加当前登录的用户 我可以在文件中附加一个字符串,但在尝试执行req.user时,它会声明 无法读取未定义的属性“user” 我需要在这个文件中包括什么,以便它知道user是什么 let fs = require("fs"), express = require(&

我试图找到一种方法来获取当前登录的用户,然后将其附加到JSON文件中。下面是我的代码,首先读取目录,然后获取最新的文件,返回它,然后附加当前登录的用户

我可以在文件中附加一个字符串,但在尝试执行
req.user
时,它会声明

无法读取未定义的属性“user”

我需要在这个文件中包括什么,以便它知道
user
是什么

let fs                    = require("fs"),
        express               = require("express"),
        _                     = require("underscore"),
        User                  = require("./models/user"),
        path                  = require("path");
    
    let getFileAddUser = () => { 
        let filePath = '../automation_projects/wss-automation-u/results/temp/';
        fs.readdir(filePath, (err, files) => {
            if (err) { throw err; }
            let file = getMostRecentFile(files, filePath);
            console.log(file);
            fs.readFile(filePath + file, 'utf8', (err, data) => {
                let json = JSON.parse(data);
                if(err){
                    console.error(err);
                    return;
                } else {
                    //Un-comment to write to most recent file.
                    //==================================================
                    //This should find the currently logged in user and append them to the most recent file found.
                    json.currentuser = req.user;
                    fs.writeFile(filePath + file, JSON.stringify(json), (error) => {
                        if(error){
                            console.error(error);
                            return;
                        } else {
                            console.log(json);
                        }
                    });
                    //==================================================
                    console.log(data);
                }
            });
        });
    };
    
    //Get the most recent file from the results folder.
    function getMostRecentFile(files, path) {
        let out = [];
        files.forEach(function(file) {
            let stats = fs.statSync(path + "/" +file);
            if(stats.isFile()) {
                out.push({"file":file, "mtime": stats.mtime.getTime()});
            }
        });
        out.sort(function(a,b) {
            return b.mtime - a.mtime;
        })
        return (out.length>0) ? out[0].file : "";
    }
    
    module.exports = getFileAddUser;

多亏了一位知识渊博的同事和一些进一步的研究,我们才得以实现这一目标。我想与大家分享一下我们为将当前登录的用户附加到结果文件中而编写的代码。您还会注意到我们在使用华美达.js库时得到了一些帮助

let fs                    = require("fs"),
    express               = require("express"),
    _                     = require("underscore"),
    User                  = require("./models/user"),
    r                     = require("ramda"),
    path                  = require("path");



 //This will be our function to get the most recent file from our dir and 
      //return it to us. We than user this function below.
function getMostRecentFile(files, path) {
    let out = [];
    let f = r.tail(files);
    console.log(files);
    f.forEach(function(file) {
        let stats = fs.statSync(path + "/" +file);
        if(stats.isFile()) {
            out.push({"file":file, "mtime": stats.mtime.getTime()});
        }
    });
    out.sort(function(a,b) {
        return b.mtime - a.mtime;
    })
    return (out.length>0) ? out[0].file : "";
}

//Passing in 'u' as a argument which can than be used in a route and pass in 
//anything that we want it to be. In our case it was the currently logged 
//in user.
let getUser = (u) => {
    let user = u;
    let filePath = '../automation_projects/wss-automation-u/results/temp/';
    //Comment above and uncomment below for testing locally.
    // let filePath = "./temp/";
    let file = "";
     //Below we read our dir then get the most recent file using the 
    //getMostRecentfile function above.
    read_directory(filePath).then( files => {
        file = getMostRecentFile(files, filePath)
        console.log(file);
        return(read_file(filePath + file))
    }).then( x => {
    // Here we parse through our data with x representing the data that we 
    //returned above.
            let json = JSON.parse(x);
            return new Promise(function(resolve, reject) {
            json.currentuser = u;
            //And finally we write to the end of the latest file.
            fs.writeFile(filePath + file, JSON.stringify(json), (error) => {
                if(error) reject(error);
                else resolve(json);
                // console.log(json);
            });
        });
    });
}

let read_directory = (path) => {
    return new Promise((resolve, reject) => {
      fs.readdir(path, (err, items) => {
        if (err){
          return reject(err)
        }
        return resolve([path, ...items])
      })
    })
   }

   let read_file = (path) => {
    return new Promise((resolve, reject) => {
      fs.readFile(path, "utf8", (err, items) => {
        if (err){
          return reject(err)
        }
        return resolve(items)
      })
    })
   }

   module.exports = getUser;
下面是如何使用getUser模块的示例路由。您需要它,就像使用node.js和依赖项做其他事情一样。希望这对将来的人有所帮助

let getUser = require("getuser");


//Make a route to use the getUser module and pass in our argument value.
app.get("/", (req, res) => {
//With in the get user function pass in whatever you want to equal 'u' from the getuser module.
   getUser(req.user.username);
   res.render("index", { username: req.user });
});

fs.readFile(文件路径+文件'utf8',(错误、数据、请求)
那里有什么
req
功能?回调函数只有两个参数
error,data
好的,那么如何从模块中捕获当前登录的用户?创建一个路由。从前端点击此路由并将一些信息发送到此路由。然后执行您希望它执行的任何操作