Created
October 29, 2023 04:22
-
-
Save maietta/1763640a2dcd5970196cbaa0cc26ea00 to your computer and use it in GitHub Desktop.
Simple get/set key value store for SvelteKit, etc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const keyValueStore = new KeyValueStore('./key-value-store.txt'); | |
// Get a value from the store | |
const value = await keyValueStore.get('key1'); | |
// Set a value in the store | |
await keyValueStore.set('key2', 'value2'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs'; | |
export class KeyValueStore { | |
private filePath: string; | |
constructor(filePath: string) { | |
this.filePath = filePath; | |
} | |
public async get(key: string): Promise<string | undefined> { | |
try { | |
const data = await fs.promises.readFile(this.filePath, 'utf-8'); | |
const keyValuePairs = data.split('\n'); | |
const keyValuePair = keyValuePairs.find((pair) => pair.startsWith(key)); | |
if (keyValuePair) { | |
return keyValuePair.split(':')[1]; | |
} | |
return undefined; | |
} catch (error) { | |
return undefined; | |
} | |
} | |
public async set(key: string, value: string): Promise<void> { | |
try { | |
const data = await fs.promises.readFile(this.filePath, 'utf-8'); | |
const keyValuePairs = data.split('\n'); | |
const existingKeyValuePair = keyValuePairs.find((pair) => pair.startsWith(key)); | |
if (existingKeyValuePair) { | |
const newKeyValuePairs = keyValuePairs.filter((pair) => pair !== existingKeyValuePair); | |
newKeyValuePairs.push(`${key}:${value}`); | |
await fs.promises.writeFile(this.filePath, newKeyValuePairs.join('\n'), 'utf-8'); | |
} else { | |
await fs.promises.appendFile(this.filePath, `${key}:${value}\n`, 'utf-8'); | |
} | |
} catch (error) { | |
console.error(error); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment