consoleiq
Version:
Enhanced console logging with remote capabilities
84 lines (77 loc) • 2.4 kB
JavaScript
/**
* Storage utility for caching logs
* @module storage
*/
const fs = require('fs');
const path = require('path');
const CACHE_FILE = '.consoleiq_cache.json';
const storage = {
/**
* Save logs to the cache
* @param {Array} logs - Logs to save
*/
save(logs) {
if (typeof window !== 'undefined' && window.localStorage) {
try {
const existing = JSON.parse(window.localStorage.getItem('consoleiq_cache')) || [];
const updated = existing.concat(logs);
window.localStorage.setItem('consoleiq_cache', JSON.stringify(updated));
} catch (e) {
console.error('ConsoleIQ: Failed to save logs to localStorage', e);
}
} else if (typeof process !== 'undefined') {
try {
const cachePath = path.join(process.cwd(), CACHE_FILE);
const existing = fs.existsSync(cachePath) ? JSON.parse(fs.readFileSync(cachePath)) : [];
const updated = existing.concat(logs);
fs.writeFileSync(cachePath, JSON.stringify(updated));
} catch (e) {
console.error('ConsoleIQ: Failed to save logs to file', e);
}
}
},
/**
* Load logs from the cache
* @returns {Array} - Cached logs
*/
load() {
if (typeof window !== 'undefined' && window.localStorage) {
try {
return JSON.parse(window.localStorage.getItem('consoleiq_cache')) || [];
} catch (e) {
console.error('ConsoleIQ: Failed to load logs from localStorage', e);
return [];
}
} else if (typeof process !== 'undefined') {
try {
const cachePath = path.join(process.cwd(), CACHE_FILE);
if (fs.existsSync(cachePath)) {
return JSON.parse(fs.readFileSync(cachePath));
}
return [];
} catch (e) {
console.error('ConsoleIQ: Failed to load logs from file', e);
return [];
}
}
return [];
},
/**
* Clear the cache
*/
clear() {
if (typeof window !== 'undefined' && window.localStorage) {
window.localStorage.removeItem('consoleiq_cache');
} else if (typeof process !== 'undefined') {
try {
const cachePath = path.join(process.cwd(), CACHE_FILE);
if (fs.existsSync(cachePath)) {
fs.unlinkSync(cachePath);
}
} catch (e) {
console.error('ConsoleIQ: Failed to clear log cache file', e);
}
}
}
};
module.exports = storage;