or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-node-json-db

Database using JSON file as storage for Node.JS

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/node-json-db@2.3.x

To install, run

npx @tessl/cli install tessl/npm-node-json-db@2.3.0

0

# Node JSON DB

1

2

Node JSON DB is a lightweight JSON file-based database solution for Node.js applications that need simple persistent data storage without the complexity of traditional databases. It offers a filesystem-based storage approach using JSON files with a JavaScript Object interface, supporting async/await operations, DataPath traversal similar to XMLPath for accessing nested properties, and includes features like file locking for concurrent access protection.

3

4

## Package Information

5

6

- **Package Name**: node-json-db

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install node-json-db`

10

11

## Core Imports

12

13

```typescript

14

import { JsonDB, Config } from "node-json-db";

15

```

16

17

For advanced usage with custom adapters:

18

19

```typescript

20

import { JsonDB, ConfigWithAdapter, IAdapter, JsonAdapter, FileAdapter } from "node-json-db";

21

```

22

23

Error handling imports:

24

25

```typescript

26

import { DatabaseError, DataError } from "node-json-db";

27

```

28

29

CommonJS:

30

31

```javascript

32

const { JsonDB, Config } = require("node-json-db");

33

```

34

35

## Basic Usage

36

37

```typescript

38

import { JsonDB, Config } from "node-json-db";

39

40

// Create database with file-based storage

41

// Parameters: filename, saveOnPush, humanReadable, separator, syncOnSave

42

const db = new JsonDB(new Config("myDatabase", true, false, "/"));

43

44

// Store data using DataPath (XMLPath-like syntax)

45

await db.push("/users/1", {

46

name: "Alice",

47

email: "alice@example.com",

48

age: 25

49

});

50

51

// Retrieve data

52

const user = await db.getData("/users/1");

53

console.log(user.name); // "Alice"

54

55

// Check if data exists

56

const exists = await db.exists("/users/1");

57

58

// Update with merge (non-destructive)

59

await db.push("/users/1", { active: true }, false);

60

61

// Delete data

62

await db.delete("/users/1");

63

```

64

65

## Architecture

66

67

Node JSON DB is built around several key components:

68

69

- **JsonDB Class**: Main database interface providing all CRUD operations and data access methods

70

- **DataPath System**: XMLPath-like string navigation for accessing nested data (e.g., "/users/1/profile/name")

71

- **Adapter Pattern**: Pluggable storage backends with built-in JSON file adapter and support for custom adapters

72

- **Configuration System**: Flexible configuration through `Config` class or `ConfigWithAdapter` for custom setups

73

- **Locking Mechanism**: Read/write locks for safe concurrent access using the `rwlock` library

74

- **Array Support**: Advanced array indexing including negative indices, append operations, and multi-dimensional arrays

75

- **Type Safety**: Full TypeScript support with generic methods and comprehensive type definitions

76

77

## Capabilities

78

79

### Database Operations

80

81

Core CRUD operations for managing data in the JSON database, including data retrieval, storage, updates, and deletion with DataPath navigation.

82

83

```typescript { .api }

84

class JsonDB {

85

constructor(config: JsonDBConfig);

86

87

// Data retrieval

88

getData(dataPath: string): Promise<any>;

89

getObject<T>(dataPath: string): Promise<T>;

90

getObjectDefault<T>(dataPath: string, defaultValue?: T): Promise<T>;

91

exists(dataPath: string): Promise<boolean>;

92

93

// Data modification

94

push(dataPath: string, data: any, override?: boolean): Promise<void>;

95

delete(dataPath: string): Promise<void>;

96

}

97

```

98

99

[Database Operations](./database-operations.md)

100

101

### Configuration and Adapters

102

103

Flexible configuration system with built-in file storage adapter and support for custom storage backends through the adapter pattern.

104

105

```typescript { .api }

106

class Config implements JsonDBConfig {

107

constructor(

108

filename: string,

109

saveOnPush?: boolean,

110

humanReadable?: boolean,

111

separator?: string,

112

syncOnSave?: boolean

113

);

114

}

115

116

interface IAdapter<T> {

117

readAsync(): Promise<T | null>;

118

writeAsync(data: T): Promise<void>;

119

}

120

```

121

122

[Adapters and Configuration](./adapters.md)

123

124

### Advanced Features

125

126

Advanced functionality including array operations, search capabilities, database management, locking, and path utilities for complex data scenarios.

127

128

```typescript { .api }

129

class JsonDB {

130

// Array operations

131

count(dataPath: string): Promise<number>;

132

getIndex(dataPath: string, searchValue: string | number, propertyName?: string): Promise<number>;

133

getIndexValue(dataPath: string, searchValue: string | number): Promise<number>;

134

135

// Search operations

136

filter<T>(rootPath: string, callback: FindCallback): Promise<T[] | undefined>;

137

find<T>(rootPath: string, callback: FindCallback): Promise<T | undefined>;

138

139

// Database management

140

load(): Promise<void>;

141

save(force?: boolean): Promise<void>;

142

reload(): Promise<void>;

143

144

// Path utilities

145

fromPath(path: string, propertyName?: string): Promise<string>;

146

}

147

148

type FindCallback = (entry: any, index: number | string) => boolean;

149

```

150

151

[Advanced Features](./advanced-features.md)

152

153

## Error Handling

154

155

The library provides comprehensive error handling with specific error types:

156

157

```typescript { .api }

158

class DatabaseError extends NestedError {

159

constructor(message: string, id: Number, inner?: Error);

160

}

161

162

class DataError extends NestedError {

163

constructor(message: string, id: Number, inner?: Error);

164

}

165

166

abstract class NestedError extends Error {

167

readonly inner?: Error;

168

readonly id: Number;

169

toString(): string;

170

}

171

```

172

173

Common error scenarios:

174

- **DataError**: Invalid DataPath, array index out of bounds, type mismatches

175

- **DatabaseError**: File I/O errors, JSON parsing errors, database loading/saving failures

176

177

## Core Types

178

179

```typescript { .api }

180

interface JsonDBConfig {

181

readonly adapter: IAdapter<any>;

182

readonly saveOnPush: boolean;

183

readonly separator: string;

184

}

185

186

type FindCallback = (entry: any, index: number | string) => boolean;

187

```