日期:2014-05-16  浏览次数:20394 次

Javascript解析INI文件内容的函数

.ini 是Initialization File的缩写,即初始化文件,ini文件格式广泛用于软件的配置文件。

INI文件由节、键、值、注释组成。

根据node.js版本的node-iniparser改写了个Javascript函数来解析INI文件内容,传入INI格式的字符串,返回一个json object。

    function parseINIString(data){
        var regex = {
            section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
            param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
            comment: /^\s*;.*$/
        };
        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;
    }

测试INI内容:


返回结果对象: