corrade-nucleus-nucleons – Blame information for rev 20

Subversion Repositories:
Rev:
Rev Author Line No. Line
20 office 1 // Based on iniparser by shockie <https://npmjs.org/package/iniparser>
2  
3 /*
4 * get the file handler
5 */
6 var fs = require('fs');
7  
8 /*
9 * define the possible values:
10 * section: [section]
11 * param: key=value
12 * comment: ;this is a comment
13 */
14 var regex = {
15 section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
16 param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
17 comment: /^\s*[#;].*$/
18 };
19  
20 /*
21 * parses a .ini file
22 * @param: {String} file, the location of the .ini file
23 * @param: {Function} callback, the function that will be called when parsing is done
24 * @return: none
25 */
26 module.exports.parse = function (file, callback) {
27 if (!callback) {
28 return;
29 }
30 fs.readFile(file, 'utf8', function (err, data) {
31 if (err) {
32 callback(err);
33 } else {
34 callback(null, parse(data));
35 }
36 });
37 };
38  
39 module.exports.parseSync = function (file) {
40 return parse(fs.readFileSync(file, 'utf8'));
41 };
42  
43 function parse (data) {
44 var sectionBody = {};
45 var sectionName = null;
46 var value = [[sectionName, sectionBody]];
47 var lines = data.split(/\r\n|\r|\n/);
48 lines.forEach(function (line) {
49 var match;
50 if (regex.comment.test(line)) {
51 return;
52 } else if (regex.param.test(line)) {
53 match = line.match(regex.param);
54 sectionBody[match[1]] = match[2];
55 } else if (regex.section.test(line)) {
56 match = line.match(regex.section);
57 sectionName = match[1];
58 sectionBody = {};
59 value.push([sectionName, sectionBody]);
60 }
61 });
62 return value;
63 }
64  
65 module.exports.parseString = parse;