-
Notifications
You must be signed in to change notification settings - Fork 1
/
node-iniparser.js
66 lines (61 loc) · 1.35 KB
/
node-iniparser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* get the file handler
*/
var fs = require('fs');
/*
* define the possible values:
* section: [section]
* param: key=value
* comment: ;this is a comment
*/
var regex = {
section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
comment: /^\s*;.*$/
};
/*
* parses a .ini file
* @param: {String} file, the location of the .ini file
* @param: {Function} callback, the function that will be called when parsing is done
* @return: none
*/
module.exports.parse = function(file, callback){
if(!callback){
return;
}
fs.readFile(file, 'utf8', function(err, data){
if(err){
callback(err);
}else{
callback(null, parse(data));
}
});
};
module.exports.parseSync = function(file){
return parse(fs.readFileSync(file, 'utf8'));
};
function parse(data){
var value = {};
var lines = data.split(/\r\n|\r|\n/);
var section = null;
lines.forEach(function(line){
if(regex.comment.test(line)){
return;
}else if(regex.param.test(line)){
var match = line.match(regex.param);
if(section){
value[section][match[1]] = match[2];
}else{
value[match[1]] = match[2];
}
}else if(regex.section.test(line)){
var match = line.match(regex.section);
value[match[1]] = {};
section = match[1];
}else if(line.length == 0 && section){
section = null;
};
});
return value;
}
module.exports.parseString = parse;