webdriver | selenium client | webdriver test | Search

The code is designed to manage sessions by reading and writing data to a sessions.json file, utilizing environment variables and file system modules. It exports two functions, readSessions and updateOrAddSession, which handle reading and updating the sessions array, respectively.

Run example

npm run import -- "selenium session"

selenium session


const fs = require('fs');

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

let sessions = [];
let 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;
}


function updateOrAddSession(currentSession) {
    const sessions = readSessions();

    if (!currentSession) {
        return sessions;
    }
    // don't update sessions while scanning
    const updateSession = sessions.filter(s => s[1] === currentSession)[0];
    if (typeof updateSession !== 'undefined') {
        console.log('update ' + currentSession);
        updateSession[0] = (new Date()).getTime();
    } else {
        console.log('insert ' + currentSession);
        const oldSession = sessions[sessions.length] = [];
        // http://www.english.upenn.edu/~jenglish/English104/tzara.html
        oldSession[1] = currentSession;
        oldSession[0] = (new Date()).getTime();
    }
    console.log('writing ' + SESSIONS_PATH)
    fs.writeFileSync(
        SESSIONS_PATH,
        JSON.stringify(sessions, null, 4));
    return sessions;
}


module.exports = {
    updateOrAddSession,
    readSessions,
}

What the code could have been:

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

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

// Initialize variables
let sessions = [];
let sessionModified = 0;

/**
 * Reads sessions from the file system.
 * @returns {Array} Sessions
 */
async function readSessions() {
    try {
        if (await fs.access(SESSIONS_PATH)) {
            const stats = await fs.stat(SESSIONS_PATH);
            if (stats.mtime.getTime() > sessionModified) {
                sessionModified = stats.mtime.getTime();
                sessions = JSON.parse(await fs.readFile(SESSIONS_PATH, 'utf8'));
            }
        }
    } catch (error) {
        // Error handling for file access or parsing
        sessions = [];
        console.error('Error reading sessions:', error);
    }
    return sessions;
}

/**
 * Updates or adds a session to the sessions array.
 * @param {Array} currentSession Current session to update or add
 * @returns {Array} Sessions
 */
async function updateOrAddSession(currentSession) {
    // Read sessions from file system
    const sessions = await readSessions();

    // If no current session, return empty sessions array
    if (!currentSession) {
        return sessions;
    }

    // Check if session already exists in sessions array
    const updateSession = sessions.find((session) => session[1] === currentSession);
    if (updateSession) {
        console.log(`Updating session: ${currentSession}`);
        updateSession[0] = new Date().getTime();
    } else {
        console.log(`Adding new session: ${currentSession}`);
        const newSession = [new Date().getTime(), currentSession];
        sessions.push(newSession);
    }

    try {
        // Write updated sessions to file system
        await fs.writeFile(SESSIONS_PATH, JSON.stringify(sessions, null, 4));
        return sessions;
    } catch (error) {
        // Error handling for file write
        console.error('Error writing sessions:', error);
        return sessions;
    }
}

module.exports = {
    updateOrAddSession,
    readSessions,
};

Code Breakdown

Dependencies and Constants

Functions

readSessions()

updateOrAddSession(currentSession)

Module Exports