or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# RC

1

2

RC is a hardwired configuration loader for Node.js applications that automatically discovers and merges configuration from multiple sources including command line arguments, environment variables, configuration files in various formats (JSON and INI), and default values. It follows Unix-style configuration conventions with a predictable precedence order where command line arguments override environment variables, which override configuration files, which override defaults.

3

4

## Package Information

5

6

- **Package Name**: rc

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install rc`

10

11

## Core Imports

12

13

```javascript

14

const rc = require('rc');

15

```

16

17

For ESM:

18

19

```javascript

20

import rc from 'rc';

21

```

22

23

## Basic Usage

24

25

```javascript

26

const rc = require('rc');

27

28

// Basic usage: provide app name and defaults

29

const config = rc('myapp', {

30

port: 8080,

31

host: 'localhost',

32

debug: false

33

});

34

35

console.log(config);

36

// Loads config from:

37

// 1. Command line: --port 3000 --debug

38

// 2. Environment: myapp_port=3000 myapp_debug=true

39

// 3. Config files: .myapprc, ~/.myapprc, /etc/myapprc

40

// 4. Defaults: { port: 8080, host: 'localhost', debug: false }

41

```

42

43

## Capabilities

44

45

### Configuration Loading

46

47

Main configuration loader that discovers and merges configuration from multiple sources with Unix-style precedence rules.

48

49

```javascript { .api }

50

/**

51

* Load and merge configuration from multiple sources

52

* @param {string} name - Application name for config file discovery

53

* @param {object|string} [defaults] - Default configuration object or JSON string

54

* @param {object} [argv] - Custom parsed argv object (defaults to process.argv)

55

* @param {function} [parse] - Custom parser function for config files

56

* @returns {object} Merged configuration object with optional configs/config properties

57

* @throws {Error} If name is not a string

58

*/

59

function rc(name, defaults, argv, parse);

60

```

61

62

**Configuration Sources (in precedence order):**

63

64

1. **Command line arguments** - Parsed by minimist (e.g., `--foo bar`, `--nested.key=value`)

65

2. **Environment variables** - Prefixed with `${appname}_` (e.g., `myapp_port=3000`)

66

- Use `__` for nested properties (e.g., `myapp_db__host=localhost``db.host`)

67

3. **Custom config file** - Specified via `--config path/to/file`

68

4. **Local config files** - `.${appname}rc` (searches up directory tree)

69

5. **User config files**:

70

- `$HOME/.${appname}rc`

71

- `$HOME/.${appname}/config`

72

- `$HOME/.config/${appname}`

73

- `$HOME/.config/${appname}/config`

74

6. **System config files** (Unix only):

75

- `/etc/${appname}rc`

76

- `/etc/${appname}/config`

77

7. **Default values** - Object passed to rc function

78

79

**Usage Examples:**

80

81

```javascript

82

const rc = require('rc');

83

84

// Simple usage with defaults

85

const conf = rc('myapp', {

86

port: 2468,

87

views: {

88

engine: 'jade'

89

}

90

});

91

92

// Custom argv parsing

93

const customConf = rc('myapp', defaults, {

94

port: 3000,

95

debug: true,

96

_: []

97

});

98

99

// Custom file parser

100

const strictConf = rc('myapp', defaults, null, (content) => {

101

return JSON.parse(content); // Only allow valid JSON

102

});

103

```

104

105

### Browser Configuration Loading

106

107

Browser-only version that simply returns defaults since file system access is not available.

108

109

```javascript { .api }

110

/**

111

* Browser version - returns defaults only (no file system access)

112

* @param {string} name - Application name (ignored in browser)

113

* @param {object} [defaults] - Default configuration object

114

* @returns {object} The defaults object

115

*/

116

function rc(name, defaults);

117

```

118

119

**Usage:**

120

121

```html

122

<script src="node_modules/rc/browser.js"></script>

123

<script>

124

// Browser usage

125

const config = rc('myapp', { theme: 'light' });

126

// Returns: { theme: 'light' }

127

</script>

128

```

129

130

### Command Line Interface

131

132

Executable CLI tool that loads configuration for a specified application and outputs JSON.

133

134

```bash { .api }

135

# Load config for specified app and output JSON

136

rc <appname>

137

138

# Example

139

rc myapp

140

# Outputs JSON configuration for 'myapp'

141

```

142

143

## Configuration File Formats

144

145

RC supports both JSON and INI format configuration files without file extensions:

146

147

**JSON Format (supports comments):**

148

149

```json

150

{

151

// Comments are supported via strip-json-comments

152

"port": 3000,

153

"database": {

154

"host": "localhost",

155

"port": 5432

156

}

157

}

158

```

159

160

**INI Format:**

161

162

```ini

163

; Comments supported in INI format

164

port=3000

165

166

[database]

167

host=localhost

168

port=5432

169

170

; Nested sections supported

171

[server.ssl]

172

enabled=true

173

cert=/path/to/cert.pem

174

```

175

176

## Return Object Structure

177

178

The configuration object returned by `rc()` contains:

179

180

```javascript { .api }

181

interface ConfigResult {

182

// All merged configuration properties

183

[key: string]: any;

184

185

// Array of paths to config files that were found and loaded

186

configs?: string[];

187

188

// Path to the last (highest precedence) config file used

189

config?: string;

190

191

// Remaining command line arguments from minimist

192

_?: string[];

193

}

194

```

195

196

**Example return object:**

197

198

```javascript

199

{

200

"port": "3001",

201

"mode": "test",

202

"foo": "bar",

203

"_": [],

204

"configs": [

205

"/Users/user/myproject/.myapprc",

206

"/Users/user/.myapprc"

207

],

208

"config": "/Users/user/.myapprc"

209

}

210

```

211

212

## Environment Variable Mapping

213

214

Environment variables are mapped to configuration properties using the following rules:

215

216

```javascript

217

// Environment variable → Configuration property

218

myapp_port=3000 → { port: "3000" }

219

myapp_db__host=localhost → { db: { host: "localhost" } }

220

myapp_ssl__cert__path=/x → { ssl: { cert: { path: "/x" } } }

221

```

222

223

## Type Handling

224

225

**Important**: Configuration values from files and environment variables are always strings. Use type conversion utilities for strict type checking:

226

227

```javascript

228

const config = rc('myapp', { port: 8080 });

229

230

// Convert strings to proper types

231

config.port = parseInt(config.port) || config.port;

232

config.debug = config.debug === 'true';

233

config.timeout = parseFloat(config.timeout) || config.timeout;

234

235

// Or use a utility like parse-strings-in-object

236

const parseStrings = require('parse-strings-in-object');

237

const typedConfig = parseStrings(config);

238

```

239

240

## Error Handling

241

242

RC throws errors in the following cases:

243

244

- **Invalid app name**: If the first parameter is not a string

245

- **File parsing errors**: If config files contain invalid JSON/INI syntax

246

- **File system errors**: If config files exist but cannot be read due to permissions

247

248

```javascript

249

try {

250

const config = rc('myapp', defaults);

251

} catch (error) {

252

if (error.message.includes('name *must* be string')) {

253

console.error('App name must be a string');

254

}

255

// Handle other configuration loading errors

256

}

257

```

258

259

## Performance Notes

260

261

RC uses synchronous file system operations (`fs.statSync`), so avoid using it in hot code paths such as request handlers. Load configuration once at application startup:

262

263

```javascript

264

// Good: Load once at startup

265

const config = rc('myapp', defaults);

266

267

app.listen(config.port, () => {

268

console.log(`Server running on port ${config.port}`);

269

});

270

271

// Bad: Don't load in request handlers

272

app.get('/api/data', (req, res) => {

273

const config = rc('myapp', defaults); // Avoid this!

274

// ...

275

});

276

```