Skip to content

Commit 5c78c45

Browse files
silentrobry
authored andcommitted
Added Parse INI to Node, tests
1 parent 939a6c7 commit 5c78c45

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

lib/ini.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
exports.parse = function(d) {
2+
var trim = function(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }
3+
var ini = {'-':{}};
4+
5+
var section = '-';
6+
7+
var lines = d.split('\n');
8+
for (var i=0; i<lines.length; i++) {
9+
10+
var re = /(.*)=(.*)|\[([a-z:\.0-9_\s]+)\]/i;
11+
12+
var match = lines[i].match(re);
13+
if (match != null) {
14+
if (match[3] != undefined) {
15+
section = match[3];
16+
ini[section] = {};
17+
} else {
18+
var key = trim(match[1]);
19+
var value = trim(match[2]);
20+
ini[section][key] = value;
21+
}
22+
}
23+
}
24+
25+
return ini;
26+
}

test/fixtures/fixture.ini

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
root=something
2+
3+
[section]
4+
one=two
5+
Foo=Bar
6+
this=Your Mother!
7+
blank=
8+
9+
[Section Two]
10+
something else=blah
11+
remove = whitespace

test/simple/test-ini.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
process.mixin(require("../common"));
2+
require("fs");
3+
parse = require("ini").parse;
4+
5+
debug("load fixtures/fixture.ini");
6+
7+
p = path.join(fixturesDir, "fixture.ini");
8+
9+
fs.readFile(p,function(err, data) {
10+
if (err) throw err;
11+
12+
assert.equal(typeof parse, 'function');
13+
14+
var iniContents = parse(data);
15+
assert.equal(typeof iniContents, 'object');
16+
assert.deepEqual(iniContents,{"-":{"root":"something"},"section":{"one":"two","Foo":"Bar","this":"Your Mother!","blank":""},"Section Two":{"something else":"blah","remove":"whitespace"}})
17+
18+
assert.equal(iniContents['-']['root'],'something');
19+
assert.equal(iniContents['section']['blank'],'');
20+
assert.equal(iniContents['Section Two']['remove'],'whitespace');
21+
22+
});

0 commit comments

Comments
 (0)