webdriver | Cell 9 | Cell 11 | Search

This code defines a module that reads session data from a JSON file at SESSIONS_PATH and returns an array of session data. It also includes error handling to reset the session array if an error occurs while reading the file.

Cell 10

var fs = require('fs');
var path = require('path');

var TOKEN_DIR = path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.credentials');
var SESSIONS_PATH = path.join(TOKEN_DIR, 'sessions.json');

var sessions = [];
var sessionModified = 0;

function readSessions() {
    try {
        if(fs.existsSync(SESSIONS_PATH)
           && fs.statSync(SESSIONS_PATH).mtime.getTime() > sessionModified) {
            sessionModified = fs.statSync(SESSIONS_PATH).mtime.getTime();
            sessions = JSON.parse(fs.readFileSync(SESSIONS_PATH)
                .toString());
        }
    } catch (e) {
        sessions = [];
    }
    return sessions;
};
module.exports = readSessions;

What the code could have been:

const fs = require('fs').promises;
const path = require('path');

const TOKEN_DIR = path.join(
  process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
  '.credentials'
);
const SESSIONS_PATH = path.join(TOKEN_DIR,'sessions.json');

let sessions = [];
let sessionModified = 0;

/**
 * Reads sessions from the JSON file at SESSIONS_PATH.
 * If the file is newer than the last modification, it is updated.
 * @returns {Promise} An array of session objects.
 */
async function readSessions() {
  try {
    // Check if the sessions file exists and is newer than the last modification
    if (await fs.access(SESSIONS_PATH)) {
      const stats = await fs.stat(SESSIONS_PATH);
      if (stats.mtimeMs > sessionModified) {
        // Update sessionModified and sessions
        sessionModified = stats.mtimeMs;
        sessions = JSON.parse(await fs.readFile(SESSIONS_PATH, 'utf8'));
      }
    }
  } catch (e) {
    // If an error occurs, reset sessions to an empty array
    sessions = [];
  }
  return sessions;
}

module.exports = readSessions;

Code Breakdown

Module Dependencies

Constants

Variables

Function: readSessions()

  1. Checks if the'sessions.json' file exists and has been modified since the last read.
  2. If the file exists and has been modified, reads its contents, parses it as JSON, and updates the sessions array.
  3. Returns the sessions array.

Error Handling

Export