Добавить зарегистрированного пользователя в файл JSON - PullRequest
0 голосов
/ 01 мая 2018

Здравствуйте. Я пытаюсь найти способ получить пользователя, вошедшего в систему, и добавить его в файл JSON. Ниже приведен мой код, который сначала читает каталог, затем получает самый последний файл, возвращает его и затем добавляет текущего пользователя, который вошел в систему. Я могу добавить строку в файл, но при попытке выполнить req.user есть состояния «Cannot» прочитать свойство 'пользователь' из неопределенного ". Что мне нужно включить в этот файл, чтобы он знал, кто такой пользователь? Спасибо заранее.

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;

1 Ответ

0 голосов
/ 04 мая 2018

Благодаря хорошо осведомленному сотруднику и некоторым дополнительным исследованиям мы смогли заставить это работать. Я хотел бы поделиться кодом, который мы придумали, чтобы добавить зарегистрированного пользователя в наш файл результатов. Вы также заметите, что мы получили некоторую помощь при использовании библиотеки Ramada.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 });
});
...