import { IStorage } from "@exceptionless/core" ; import { mkdirSync } from "fs" ; import { readdir , readFile , unlink , writeFile } from "fs/promises" ; import { dirname , join , resolve } from "path" ; import { argv } from "process" ; export class NodeDirectoryStorage implements IStorage { private directory : string ; constructor ( directory ? ) { if ( ! directory ) { this . directory = argv && argv . length > 1 ? join ( dirname ( argv [ 1 ] ) , ".exceptionless" ) : ".exceptionless" ; } else { this . directory = resolve ( directory ) ; } mkdirSync ( this . directory , { recursive : true } ) ; } public async length ( ) { const keys = await this . keys ( ) ; return keys . length ; } public async clear ( ) { for ( const key of await this . keys ( ) ) { await this . removeItem ( key ) ; } return Promise . resolve ( ) ; } public async getItem ( key ) { try { return await readFile ( join ( this . directory , key ) , "utf8" ) ; } catch ( ex ) { if ( this . isNodeError ( ex ) && ex . code === "ENOENT" ) { return null ; } throw ex ; } } public async key ( index ) { const keys = await this . keys ( ) ; return Promise . resolve ( index < keys . length ? keys [ index ] : null ) ; } public async keys ( ) { return await readdir ( this . directory ) ; } public async removeItem ( key ) { try { await unlink ( join ( this . directory , key ) ) ; } catch ( ex ) { if ( this . isNodeError ( ex ) && ex . code !== "ENOENT" ) { throw ex ; } } } public async setItem ( key , value ) { await writeFile ( join ( this . directory , key ) , value ) ; } private isNodeError ( error ) { return typeof error === "object" ; } }