or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# load-json-file

1

2

A simple and reliable utility for reading and parsing JSON files in Node.js applications. It offers both asynchronous and synchronous APIs with built-in UTF-8 BOM stripping capabilities, ensuring proper handling of JSON files regardless of their encoding. This package is ES modules only and requires Node.js with ES module support.

3

4

## Package Information

5

6

- **Package Name**: load-json-file

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES modules only) with TypeScript definitions

9

- **Node.js Requirements**: ^12.20.0 || ^14.13.1 || >=16.0.0

10

- **Installation**: `npm install load-json-file`

11

12

## Core Imports

13

14

```javascript

15

import { loadJsonFile, loadJsonFileSync } from "load-json-file";

16

```

17

18

**Note**: This package is ES modules only and requires `import` statements. CommonJS `require()` is not supported.

19

20

## Basic Usage

21

22

```javascript

23

import { loadJsonFile, loadJsonFileSync } from "load-json-file";

24

25

// Async usage

26

const config = await loadJsonFile('config.json');

27

console.log(config);

28

29

// Sync usage

30

const packageInfo = loadJsonFileSync('package.json');

31

console.log(packageInfo.name);

32

33

// With options

34

const data = await loadJsonFile('data.json', {

35

beforeParse: jsonString => jsonString.replace(/\\/g, '/'), // Transform before parsing

36

reviver: (key, value) => key === 'date' ? new Date(value) : value // Transform values

37

});

38

```

39

40

## Capabilities

41

42

### Asynchronous JSON File Loading

43

44

Reads and parses a JSON file asynchronously with UTF-8 BOM stripping.

45

46

```javascript { .api }

47

/**

48

* Read and parse a JSON file asynchronously

49

* @param filePath - Path to the JSON file to read

50

* @param options - Optional parsing configuration

51

* @returns Promise that resolves to the parsed JSON data

52

*/

53

function loadJsonFile<ReturnValueType = JsonValue>(

54

filePath: string,

55

options?: Options

56

): Promise<ReturnValueType>;

57

```

58

59

### Synchronous JSON File Loading

60

61

Reads and parses a JSON file synchronously with UTF-8 BOM stripping.

62

63

```javascript { .api }

64

/**

65

* Read and parse a JSON file synchronously

66

* @param filePath - Path to the JSON file to read

67

* @param options - Optional parsing configuration

68

* @returns The parsed JSON data

69

*/

70

function loadJsonFileSync<ReturnValueType = JsonValue>(

71

filePath: string,

72

options?: Options

73

): ReturnValueType;

74

```

75

76

## Types

77

78

```typescript { .api }

79

/**

80

* Configuration options for JSON parsing

81

*/

82

interface Options {

83

/**

84

* Function to transform the JSON string before parsing

85

* Useful for preprocessing the raw JSON content

86

*/

87

readonly beforeParse?: BeforeParse;

88

89

/**

90

* Function to transform parsed values during JSON.parse

91

* See JSON.parse reviver parameter documentation

92

*/

93

readonly reviver?: Reviver;

94

}

95

96

/**

97

* Function type for transforming JSON string before parsing

98

*/

99

type BeforeParse = (data: string) => string;

100

101

/**

102

* Function type for JSON.parse reviver parameter

103

*/

104

type Reviver = (this: unknown, key: string, value: unknown) => unknown;

105

106

/**

107

* Represents any valid JSON value type (from type-fest)

108

*/

109

type JsonValue = string | number | boolean | null | {[Key in string]?: JsonValue} | JsonValue[];

110

```

111

112

## Usage Examples

113

114

### Basic File Loading

115

116

```javascript

117

import { loadJsonFile } from "load-json-file";

118

119

// Load configuration

120

const config = await loadJsonFile('./config.json');

121

122

// Load package.json

123

const packageInfo = await loadJsonFile('./package.json');

124

console.log(`Loading ${packageInfo.name} v${packageInfo.version}`);

125

```

126

127

### Using beforeParse Option

128

129

```javascript

130

import { loadJsonFile } from "load-json-file";

131

132

// Remove comments from JSON before parsing

133

const data = await loadJsonFile('./config-with-comments.json', {

134

beforeParse: (jsonString) => {

135

// Remove single-line comments (simplified example)

136

return jsonString.replace(/\/\/.*$/gm, '');

137

}

138

});

139

```

140

141

### Using reviver Option

142

143

```javascript

144

import { loadJsonFile } from "load-json-file";

145

146

// Transform date strings to Date objects

147

const userData = await loadJsonFile('./user-data.json', {

148

reviver: (key, value) => {

149

if (key.endsWith('Date') && typeof value === 'string') {

150

return new Date(value);

151

}

152

return value;

153

}

154

});

155

```

156

157

### Synchronous Usage

158

159

```javascript

160

import { loadJsonFileSync } from "load-json-file";

161

162

try {

163

const config = loadJsonFileSync('./config.json');

164

console.log('Config loaded:', config);

165

} catch (error) {

166

console.error('Failed to load config:', error.message);

167

}

168

```

169

170

### Type-Safe Usage with TypeScript

171

172

```typescript

173

import { loadJsonFile } from "load-json-file";

174

175

interface Config {

176

apiUrl: string;

177

timeout: number;

178

features: string[];

179

}

180

181

// Type-safe loading

182

const config = await loadJsonFile<Config>('./config.json');

183

console.log(config.apiUrl); // TypeScript knows this is a string

184

```

185

186

## Key Features

187

188

- **UTF-8 BOM Stripping**: Automatically removes UTF-8 BOM using TextDecoder for consistent parsing

189

- **Dual API**: Both async (`loadJsonFile`) and sync (`loadJsonFileSync`) versions available

190

- **Custom Transformations**: Support for `beforeParse` to modify JSON string before parsing

191

- **Reviver Support**: Full JSON.parse reviver functionality for value transformations

192

- **TypeScript Support**: Complete type definitions with generic return types

193

- **Zero Dependencies**: No external dependencies, uses only Node.js built-in modules

194

- **ES Module Only**: Pure ES module format, requires Node.js with ES module support