or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdinitialization.mdlow-level-operations.mdquery-operations.mdstorage-operations.md

storage-operations.mddocs/

0

# Data Storage Operations

1

2

Core persistence operations for storing, retrieving, updating, and removing data with optional TTL (time-to-live) support.

3

4

## Capabilities

5

6

### Set Item

7

8

Stores a key-value pair with optional TTL configuration.

9

10

```javascript { .api }

11

/**

12

* Stores a key-value pair with optional TTL configuration

13

* @param key - The key to store the value under

14

* @param value - The value to store (will be serialized)

15

* @param options - Optional configuration including TTL

16

* @returns Promise resolving to storage result

17

*/

18

async function setItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;

19

20

// Alias

21

async function set(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;

22

```

23

24

**Usage Examples:**

25

26

```javascript

27

const storage = require('node-persist');

28

await storage.init();

29

30

// Basic storage

31

await storage.setItem('username', 'alice');

32

await storage.setItem('user', { name: 'Alice', age: 30, active: true });

33

34

// With TTL in milliseconds

35

await storage.setItem('session', 'abc123', { ttl: 60000 }); // expires in 1 minute

36

await storage.setItem('temp-data', [1, 2, 3], { ttl: 5000 }); // expires in 5 seconds

37

38

// With TTL as Date object

39

const expireDate = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now

40

await storage.setItem('scheduled-task', { task: 'cleanup' }, { ttl: expireDate });

41

42

// Using alias

43

await storage.set('config', { theme: 'dark', lang: 'en' });

44

```

45

46

### Get Item

47

48

Retrieves a value by key, automatically handling expiration.

49

50

```javascript { .api }

51

/**

52

* Retrieves a value by key, automatically handling expiration

53

* @param key - The key to retrieve the value for

54

* @returns Promise resolving to the stored value or undefined if not found/expired

55

*/

56

async function getItem(key: string): Promise<any>;

57

58

// Alias

59

async function get(key: string): Promise<any>;

60

```

61

62

**Usage Examples:**

63

64

```javascript

65

// Basic retrieval

66

const username = await storage.getItem('username'); // 'alice'

67

const user = await storage.getItem('user'); // { name: 'Alice', age: 30, active: true }

68

69

// Non-existent key returns undefined

70

const missing = await storage.getItem('nonexistent'); // undefined

71

72

// Expired items return undefined (and are automatically removed)

73

const session = await storage.getItem('session'); // undefined if TTL expired

74

75

// Using alias

76

const config = await storage.get('config');

77

```

78

79

### Update Item

80

81

Updates a key's value while preserving its existing TTL, or creates a new item if the key doesn't exist or has expired.

82

83

```javascript { .api }

84

/**

85

* Updates a key's value while preserving existing TTL

86

* @param key - The key to update

87

* @param value - The new value to store

88

* @param options - Optional configuration, can override TTL

89

* @returns Promise resolving to storage result

90

*/

91

async function updateItem(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;

92

93

// Alias

94

async function update(key: string, value: any, options?: { ttl?: number | Date }): Promise<any>;

95

```

96

97

**Usage Examples:**

98

99

```javascript

100

// First, set an item with TTL

101

await storage.setItem('user', { name: 'Alice', age: 30 }, { ttl: 3600000 }); // 1 hour

102

103

// Update preserves the original TTL

104

await storage.updateItem('user', { name: 'Alice', age: 31 }); // Still expires in ~1 hour

105

106

// Update with new TTL

107

await storage.updateItem('user', { name: 'Alice', age: 32 }, { ttl: 7200000 }); // 2 hours

108

109

// If key doesn't exist, acts like setItem

110

await storage.updateItem('new-key', 'new-value'); // Creates new item

111

112

// Using alias

113

await storage.update('user', { name: 'Alice', age: 33 });

114

```

115

116

### Remove Item

117

118

Removes an item by key, deleting it from storage.

119

120

```javascript { .api }

121

/**

122

* Removes an item by key, deleting it from storage

123

* @param key - The key to remove

124

* @returns Promise resolving to removal result information

125

*/

126

async function removeItem(key: string): Promise<any>;

127

128

// Aliases

129

async function del(key: string): Promise<any>;

130

async function rm(key: string): Promise<any>;

131

```

132

133

**Usage Examples:**

134

135

```javascript

136

// Remove an item

137

await storage.removeItem('username');

138

139

// Using aliases

140

await storage.del('session');

141

await storage.rm('temp-data');

142

143

// Returns information about the removal

144

const result = await storage.removeItem('user');

145

// result: { file: '/path/to/storage/file', removed: true, existed: true }

146

147

// Removing non-existent key is safe

148

await storage.removeItem('nonexistent'); // No error thrown

149

```

150

151

### Clear All Items

152

153

Removes all items from storage, clearing the entire storage directory.

154

155

```javascript { .api }

156

/**

157

* Removes all items from storage

158

* @returns Promise resolving when all items are cleared

159

*/

160

async function clear(): Promise<void>;

161

```

162

163

**Usage Examples:**

164

165

```javascript

166

// Clear all stored data

167

await storage.clear();

168

169

// Storage is now empty

170

const keys = await storage.keys(); // []

171

const length = await storage.length(); // 0

172

```

173

174

## TTL (Time-To-Live) Behavior

175

176

### TTL Configuration

177

178

TTL can be specified in several ways:

179

180

```javascript

181

// Milliseconds from now

182

await storage.setItem('key', 'value', { ttl: 60000 }); // 1 minute

183

184

// Date object (absolute time)

185

const futureDate = new Date('2024-12-31T23:59:59Z');

186

await storage.setItem('key', 'value', { ttl: futureDate });

187

188

// Use default TTL from init options

189

await storage.init({ ttl: 3600000 }); // 1 hour default

190

await storage.setItem('key', 'value'); // Uses 1 hour TTL

191

192

// Disable TTL for specific item

193

await storage.setItem('key', 'value', { ttl: null });

194

```

195

196

### Automatic Expiration

197

198

- Expired items are automatically removed when accessed via `getItem()`

199

- Background cleanup runs at intervals set by `expiredInterval` option

200

- Manual cleanup available via `removeExpiredItems()` method

201

202

### TTL Inheritance in Updates

203

204

- `updateItem()` preserves existing TTL by default

205

- Explicitly passing `ttl` option in `updateItem()` overrides the preserved TTL

206

- If original item has expired, `updateItem()` behaves like `setItem()`

207

208

## Error Handling

209

210

Storage operations can throw errors in various scenarios:

211

212

```javascript

213

try {

214

await storage.setItem('key', 'value');

215

} catch (error) {

216

if (error.code === 'ENOSPC') {

217

console.error('No space left on device');

218

} else if (error.code === 'EACCES') {

219

console.error('Permission denied');

220

} else {

221

console.error('Storage error:', error.message);

222

}

223

}

224

```

225

226

**Common Error Scenarios:**

227

- File system errors (permissions, disk space, etc.)

228

- Invalid storage directory

229

- Corrupted storage files (when `forgiveParseErrors: false`)

230

- Write queue failures