0
# INI
1
2
An INI encoder/decoder for Node.js applications. Provides comprehensive INI file format parsing and serialization with support for nested sections, arrays, and various formatting options.
3
4
## Package Information
5
6
- **Package Name**: ini
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install ini`
10
11
## Core Imports
12
13
```javascript
14
const { parse, stringify, encode, decode, safe, unsafe } = require("ini");
15
```
16
17
For ES modules:
18
19
```javascript
20
import { parse, stringify, encode, decode, safe, unsafe } from "ini";
21
```
22
23
## Basic Usage
24
25
```javascript
26
const { parse, stringify } = require("ini");
27
28
// Parse INI text to object
29
const config = parse(`
30
scope = global
31
32
[database]
33
user = dbuser
34
password = dbpassword
35
database = use_this_database
36
37
[paths.default]
38
datadir = /var/lib/data
39
array[] = first value
40
array[] = second value
41
array[] = third value
42
`);
43
44
// Modify the object
45
config.scope = 'local';
46
config.database.database = 'use_another_database';
47
config.paths.default.tmpdir = '/tmp';
48
49
// Convert back to INI text
50
const iniText = stringify(config, { section: 'section' });
51
```
52
53
## Capabilities
54
55
### INI Parsing
56
57
Parse INI format strings into JavaScript objects with support for sections, arrays, and type conversion.
58
59
```javascript { .api }
60
/**
61
* Parse INI format string into nested JavaScript object (alias for decode)
62
* @param {string} str - INI formatted text
63
* @param {object} [opt] - Parsing options
64
* @param {boolean} [opt.bracketedArray=true] - Whether to treat keys ending with [] as arrays
65
* @returns {object} Parsed object with nested sections
66
*/
67
function parse(str, opt);
68
69
/**
70
* Parse INI format string into nested JavaScript object
71
* @param {string} str - INI formatted text
72
* @param {object} [opt] - Parsing options
73
* @param {boolean} [opt.bracketedArray=true] - Whether to treat keys ending with [] as arrays
74
* @returns {object} Parsed object with nested sections
75
*/
76
function decode(str, opt);
77
```
78
79
**Usage Examples:**
80
81
```javascript
82
const { parse } = require("ini");
83
84
// Basic parsing
85
const config = parse(`
86
name = value
87
number = 42
88
bool = true
89
`);
90
// Result: { name: 'value', number: '42', bool: true }
91
92
// Section parsing
93
const configWithSections = parse(`
94
global = setting
95
96
[section1]
97
key = value
98
99
[section2.subsection]
100
nested = deep
101
`);
102
// Result: {
103
// global: 'setting',
104
// section1: { key: 'value' },
105
// section2: { subsection: { nested: 'deep' } }
106
// }
107
108
// Array parsing with brackets
109
const configWithArrays = parse(`
110
[database]
111
hosts[] = server1
112
hosts[] = server2
113
hosts[] = server3
114
`);
115
// Result: { database: { hosts: ['server1', 'server2', 'server3'] } }
116
117
// Array parsing without brackets (duplicate keys)
118
const configDuplicateKeys = parse(`
119
[database]
120
host = server1
121
host = server2
122
host = server3
123
`, { bracketedArray: false });
124
// Result: { database: { host: ['server1', 'server2', 'server3'] } }
125
126
// Comment parsing
127
const configWithComments = parse(`
128
; This is a comment
129
# This is also a comment
130
name = value
131
; Comments are ignored
132
133
[section]
134
key = value ; inline comments work too
135
`);
136
// Result: { name: 'value', section: { key: 'value' } }
137
```
138
139
### INI Encoding
140
141
Convert JavaScript objects to INI format strings with comprehensive formatting options.
142
143
```javascript { .api }
144
/**
145
* Convert JavaScript object to INI formatted string (alias for encode)
146
* @param {object} obj - JavaScript object to encode
147
* @param {object|string} [opt] - Encoding options object or section name string
148
* @param {string} [opt.section] - Section name to prepend to all keys
149
* @param {boolean} [opt.align=false] - Align = characters (automatically enables whitespace)
150
* @param {boolean} [opt.newline=false] - Add newline after section headers
151
* @param {boolean} [opt.sort=false] - Sort sections and keys alphabetically
152
* @param {boolean} [opt.whitespace=false] - Add spaces around = characters
153
* @param {string} [opt.platform=process.platform] - Platform for line endings ('win32' for CRLF, others for LF, auto-detected)
154
* @param {boolean} [opt.bracketedArray=true] - Append [] to array keys
155
* @returns {string} INI formatted string
156
*/
157
function stringify(obj, opt);
158
159
/**
160
* Convert JavaScript object to INI formatted string
161
* @param {object} obj - JavaScript object to encode
162
* @param {object|string} [opt] - Encoding options object or section name string
163
* @param {string} [opt.section] - Section name to prepend to all keys
164
* @param {boolean} [opt.align=false] - Align = characters (automatically enables whitespace)
165
* @param {boolean} [opt.newline=false] - Add newline after section headers
166
* @param {boolean} [opt.sort=false] - Sort sections and keys alphabetically
167
* @param {boolean} [opt.whitespace=false] - Add spaces around = characters
168
* @param {string} [opt.platform=process.platform] - Platform for line endings ('win32' for CRLF, others for LF, auto-detected)
169
* @param {boolean} [opt.bracketedArray=true] - Append [] to array keys
170
* @returns {string} INI formatted string
171
*/
172
function encode(obj, opt);
173
```
174
175
**Usage Examples:**
176
177
```javascript
178
const { stringify } = require("ini");
179
180
// Basic encoding
181
const obj = {
182
global: 'setting',
183
database: {
184
host: 'localhost',
185
port: 5432
186
}
187
};
188
const basic = stringify(obj);
189
// Result:
190
// global=setting
191
// [database]
192
// host=localhost
193
// port=5432
194
195
// Encoding with section prefix
196
const withSection = stringify(obj, { section: 'app' });
197
// Result:
198
// [app]
199
// global=setting
200
// [app.database]
201
// host=localhost
202
// port=5432
203
204
// Encoding with formatting options
205
const formatted = stringify(obj, {
206
whitespace: true,
207
align: true,
208
sort: true
209
});
210
// Result (with aligned = signs and spaces):
211
// global = setting
212
// [database]
213
// host = localhost
214
// port = 5432
215
216
// Encoding arrays
217
const objWithArrays = {
218
servers: ['web1', 'web2', 'web3']
219
};
220
const withArrays = stringify(objWithArrays);
221
// Result:
222
// servers[]=web1
223
// servers[]=web2
224
// servers[]=web3
225
226
// Encoding arrays without brackets
227
const withoutBrackets = stringify(objWithArrays, { bracketedArray: false });
228
// Result:
229
// servers=web1
230
// servers=web2
231
// servers=web3
232
233
// Cross-platform line endings
234
const win32Format = stringify(obj, { platform: 'win32' });
235
// Uses CRLF line endings instead of LF
236
237
// String parameter shorthand (equivalent to { section: 'mysection' })
238
const withSection = stringify(obj, 'mysection');
239
```
240
241
**String Parameter Shorthand:**
242
243
For convenience, you can pass a string as the second parameter instead of an options object. This string will be used as the section name:
244
245
```javascript
246
// These are equivalent:
247
stringify(object, 'section')
248
stringify(object, { section: 'section' })
249
```
250
251
### String Escaping
252
253
Utilities for safely escaping and unescaping strings in INI format.
254
255
```javascript { .api }
256
/**
257
* Escape unsafe characters in strings for INI format
258
* @param {any} val - Value to make safe for INI format
259
* @returns {string} String with escaped characters
260
*/
261
function safe(val);
262
263
/**
264
* Unescape INI format strings back to original values
265
* @param {string} val - INI formatted value to unescape
266
* @returns {string} Unescaped string value
267
*/
268
function unsafe(val);
269
```
270
271
**Usage Examples:**
272
273
```javascript
274
const { safe, unsafe } = require("ini");
275
276
// Escaping unsafe strings
277
const escaped = safe('"quoted string"');
278
// Result: "\"quoted string\""
279
280
const escapedSpecial = safe('value with = and \n newline');
281
// Result: "value with = and \\n newline"
282
283
const escapedComments = safe('value ; with comment');
284
// Result: "value \\; with comment"
285
286
// Unescaping strings
287
const unescaped = unsafe('\\"safe string\\"');
288
// Result: "safe string"
289
290
const unescapedSpecial = unsafe('value \\; with \\# comment');
291
// Result: "value ; with # comment"
292
```
293
294
## Key Features
295
296
### Section Support
297
- Nested objects become INI sections `[section.subsection]`
298
- Dot-separated section names with escaping support
299
- Automatic section hierarchy handling
300
301
### Array Handling
302
- Arrays represented with bracketed notation `key[] = value` by default
303
- Alternative duplicate key format `key = value1`, `key = value2`
304
- Configurable via `bracketedArray` option
305
306
### Type Conversion
307
- Automatic parsing of boolean values (strings `'true'` and `'false'` become boolean primitives)
308
- Automatic parsing of null values (string `'null'` becomes `null`)
309
- String values preserved as strings
310
- Numeric strings remain as strings (no automatic number conversion)
311
- Only exact string matches `'true'`, `'false'`, and `'null'` are converted
312
313
### Comment Support
314
- Lines starting with `;` or `#` are treated as comments and ignored during parsing
315
- Empty lines and whitespace-only lines are also ignored
316
- Comments can appear anywhere in the INI file
317
318
### Security Features
319
- Protection against `__proto__` pollution in parsing and encoding (keys named `__proto__` are filtered out)
320
- Safe handling of escaped characters in string values
321
- Secure object creation with `Object.create(null)` to avoid prototype pollution
322
323
### Cross-Platform Support
324
- Configurable line endings (CRLF on Windows, LF elsewhere)
325
- Platform detection via `process.platform`
326
- Browser compatibility with fallback handling
327
328
### Formatting Options
329
- Configurable whitespace around `=` characters
330
- Optional alignment of `=` characters within sections
331
- Optional sorting of sections and keys
332
- Optional newlines after section headers
333
- Customizable array notation (bracketed vs duplicate keys)