[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[原创代码] JS用于操作INI格式文件的 IniObject

系统和很多软件都有用到 .ini 配置文件。它的结构比较简单,包括注释、节和参数,很容易处理。
注释都是以分号开头的,节是开头结尾是一对中括号的,参数是用等号分隔的,比如下面这个
;EXESCOPE配置内容

;注册信息
[Reg]
;用户名
Name=SpringBrother
ID=A185704471

[Window]
Left=174
Top=86
Width=594
Height=425
[DlgWin]
Left=124
Top=127
;历史记录
[Recent]

我把整个INI文件的内容称为一个 IniObject 对象,第一行是它的注释;
到第四行出现了第一个节,称为一个 Section 对象,名称为 Reg上面的第三行是它的注释;
到第六行出现了第一个参数,称为一个 Parameter 对象,他的名称为 Name,值为SpringBrother,上面的第五行是它的注释;
一直到第九行才出现第二个节,在第四行到第九行之间的所有参数都是属于 Reg 这节的。

给 IniObject、 Section、 Parameter 这三种对象定义属性和方法,使得可以读取文件内容进行转换,或者重头创建,然后可以保存,这样就可以从对象的角度,读取或者写INI文件了。
【Parameter 对象】
参数。

构造函数
Parameter(name[, value[, comments]])

属性
name         String。R/W。参数名。
value         String。R/W。参数值。
comments     String。R/W。注释。

方法
toString()     String。格式化的字符串。


【Section 对象】
节。

构造函数
Section(name[, comments])

属性
name         String。R/W。参数名。
comments     String。R/W。注释。
parameters     Array<Parameter>。R/W。包含所有的 Parameter 对象的数组。

方法
getParameterNames()             Array<String>。包含 parameters 中全部 name。
add(obj)                         this。添加一个 Parameter 对象。
add(name[, value[, comments]])     this。初始化并添加一个 Parameter 对象。
get(name)                         Parameter。根据 name 获取一个 Parameter 对象。
remove(name)                     Parameter。根据 name 删除一个 Parameter 对象。
sort(isAscOrDesc)                 this。根据 name 将所有参数正序或倒序排列。
toString()                         String。格式化的字符串。


【IniObject 对象】
整个INI文件。

构造函数
IniObject([iniFileName])

属性
comments     String。R/W。注释。
sections     Array<Section>。R/W。包含所有的 Section 对象的数组。

方法
getSectionNames()             Array<String>。包含 sections 中全部 name。
read(secName, paramName)     String。读取一个参数值。
add(obj)                     this。添加一个 Section 对象。
add(name[, comments])         this。初始化并添加一个 Section 对象。
get(name)                     Section。根据 name 获取一个 Section 对象。
remove(name)                 Section。根据 name 删除一个 Section 对象。
sort(isAscOrDesc)             this。根据 name 将所有节正序或倒序排列。
sortAll(isAscOrDesc)         this。根据 name 将所有节及其参数正序或倒序排列。
toString()                     String。格式化的字符串。
saveAs(fileName)             void。另存为文件。
save()                         void。保存。
finalize()                     void。取消对 Array 对象的更改。


以下是源代码
  1. var IniObject = function(iniFileName) {
  2.     this.__version = "1.4";
  3.     //注释。结尾无换行符
  4.     this.comments;
  5.    
  6.     //所有的节。数组元素为 Section 对象。
  7.     this.sections = [];
  8.         
  9.     //原始文件名。不可更改
  10.     var fileName;
  11.    
  12.     //各种类型的文本格式
  13.     var regExp = {
  14.             Cr          : new RegExp().compile("\\r", "g"),
  15.             CrLf        : new RegExp().compile("(\\r\\n)|[\\r\\n]", "g"),
  16.             Blank       : new RegExp().compile("^\\s*$"),
  17.             NonBlank    : new RegExp().compile("\\S"),
  18.             Useless     : new RegExp().compile("^;\\s*$", "gm"),
  19.             Trim        : new RegExp().compile("(^\\s+)|(\\s+$)", "gm"),
  20.             Comment     : new RegExp().compile("^\\s*;(.*)$"),
  21.             Section     : new RegExp().compile("^\\s*\\[([^]]+)]\\s*$"),                      //Original
  22.             Parameter     : new RegExp().compile("^(\\s*[^=]+)=(.*)$"),                          //Original
  23.             TSection     : new RegExp().compile("^\\s*\\[\\s*([^]]*[^\\s])\\s*]\\s*$"),      //Trimed Section name
  24.             TParameter     : new RegExp().compile("^\\s*([^=]*[^\\s])\\s*=(.*)$")              //Trimed Parameter name
  25.         };
  26.    
  27.     //用于较宽泛的比较
  28.     var easylize = function(str) {
  29.             if(str) {
  30.                 return str.replace(regExp.Trim, "").toLowerCase();
  31.             } else {
  32.                 return str;
  33.             }
  34.         };
  35.    
  36.     //将纯文本转换为INI文件中的注释行
  37.     var parseCommentLines = function(comments) {
  38.             var s = "";
  39.             if(comments && comments.length > 0) {
  40.                 //行首增加一个分号“;”
  41.                 s = ";" + comments.replace(regExp.CrLf, "\r;");
  42.                 //空行
  43.                 s = s.replace(regExp.Useless, "");
  44.                 //末尾换行(不能去掉这个处理,不然后面无法形成没有注释的行)
  45.                 s = s.replace(regExp.Cr, "\r\n") + "\r\n";
  46.             }
  47.             return s;
  48.         };
  49.    
  50.    
  51.     //查找一个指定name的对象在数组中的序号。找不到则返回 -1
  52.     Array.prototype.indexOf = function(paramName) {
  53.             var index = -1;
  54.             for(var i = 0; i < this.length; i++) {
  55.                 if(easylize(this[i].name) == easylize(paramName)) {
  56.                     index = i;
  57.                     break;
  58.                 }
  59.             }
  60.             return index;
  61.         };
  62.     //添加一个指定类型的对象到数组中
  63.     Array.prototype.addObject = function(objType, x, y, z) {
  64.             var obj;
  65.             if(typeof x === "object" && x.name) {
  66.                 obj = x;
  67.             } else {
  68.                 //obj = new objType(x.replace(regExp.Trim, ""), y, z);     //Trimed Object name
  69.                 obj = new objType(x, y, z);
  70.             }
  71.             var index = this.indexOf(obj.name);
  72.             if(index >= 0) {
  73.                 //覆盖
  74.                 this.splice(index, 1, obj);
  75.             } else {
  76.                 //新建
  77.                 index = this.length;
  78.                 this.push(obj);
  79.             }
  80.             //return this[index];
  81.             return this;
  82.         };
  83.     //获取一个指定name的对象
  84.     Array.prototype.getObject = function(x) {
  85.             var index = this.indexOf(x);
  86.             return index >= 0 ? this[index] : undefined;
  87.         };
  88.     //删除一个指定name的对象
  89.     Array.prototype.removeObject = function(x) {
  90.             var index = this.indexOf(x);
  91.             return index >= 0 ? this.splice(index, 1)[0] : undefined;
  92.         };
  93.     //将数组中所有对象按照name排序
  94.     Array.prototype.sortObject = function(b) {
  95.             var x = (b === undefined) ? 1 : (b ? 1 : -1);
  96.             this.sort(function(a, b) {
  97.                     return easylize(a.name) > easylize(b.name) ? x : -x;
  98.                 });
  99.         };
  100.    
  101.    
  102.     //返回包含所有节 name 的数组
  103.     this.getSectionNames = function() {
  104.             var arr = [];
  105.             for(var i = 0; i < this.sections.length; i++) {
  106.                 arr.push(this.sections[i].name);
  107.             }
  108.             return arr;
  109.         };
  110.    
  111.     //读取一个参数值
  112.     this.read = function(secName, paramName) {
  113.             var s = this.sections.getObject(secName);
  114.             if(s) {
  115.                 var p = s.get(paramName);
  116.                 if(p) {
  117.                     return p.value;
  118.                 }
  119.             }
  120.             return undefined;
  121.         };
  122.    
  123.     //添加一个节。如果已经存在则会覆盖同名的节
  124.     this.add = function(s, c) {
  125.             this.sections.addObject(Section, s, c);
  126.             return this;
  127.         };
  128.         
  129.     //获取一个 Section 对象。不存在则返回 undefined
  130.     this.get = function(secName) {
  131.             return this.sections.getObject(secName);
  132.         };
  133.    
  134.     //删除一个节并返回删除的 Section 对象
  135.     this.remove = function(secName) {
  136.             return this.sections.removeObject(secName);
  137.         };
  138.    
  139.     //将所有的节按 name 排序
  140.     this.sort = function(isAscOrDesc) {
  141.             this.sections.sortObject(isAscOrDesc);
  142.             return this;
  143.         };
  144.    
  145.     //将所有的节以及其中的参数按 name 排序
  146.     this.sortAll = function(isAscOrDesc) {
  147.             this.sort(isAscOrDesc);
  148.             for(var i = 0; i < this.sections.length; i++) {
  149.                 this.sections[i].sort(isAscOrDesc);
  150.             }
  151.             return this;
  152.         };
  153.    
  154.     //转换为 INI 文件格式的文本
  155.     this.toString = function() {
  156.             var s = parseCommentLines(this.comments);
  157.             //隔开。防止排序后误认为是 Section 的注释
  158.             if(this.comments && this.sections.length > 0) {
  159.                 s += "\r\n";
  160.             }
  161.             for(var i = 0; i < this.sections.length; i++) {
  162.                 s = s + this.sections[i].toString();
  163.             }
  164.             return s;
  165.         };
  166.    
  167.     //另存为文件
  168.     this.saveAs = function(fn) {
  169.             var fso = new ActiveXObject("Scripting.FileSystemObject");
  170.             var f = fso.OpenTextFile(fn, 2, true);
  171.             f.Write(this.toString());
  172.             f.Close();
  173.         };
  174.    
  175.     //保存文件
  176.     this.save = function() {
  177.             if(fileName) {
  178.                 this.saveAs(fileName);
  179.             } else {
  180.                 throw "File name not specified.";
  181.             }
  182.         };
  183.    
  184.     //取消对Array的更改
  185.     this.finalize = function() {
  186.             delete Array.prototype.indexOf;
  187.             delete Array.prototype.addObject;
  188.             delete Array.prototype.getObject;
  189.             delete Array.prototype.removeObject;
  190.             delete Array.prototype.sortObject;
  191.         };
  192.         
  193.    
  194.     /***************************
  195.          ;comment
  196.          name=value
  197.      ***************************/
  198.     var Parameter = function (n, v, c) {
  199.         if(n === undefined || n === null || regExp.Blank.test(n)) {
  200.             throw "The name of parameter must be specified and shouldn't be null.";
  201.             return undefined;
  202.         } else {
  203.             return {
  204.                 name : n,
  205.                 value : v === false ? "false" : v || "",
  206.                 comments : c || "",
  207.                 toString : function() {
  208.                         return (parseCommentLines(this.comments)) + this.name + "=" + this.value;
  209.                     }
  210.                 };
  211.             }
  212.         };
  213.         
  214.     /***************************
  215.          ;comment
  216.          [section]
  217.      ***************************/
  218.     var Section = function (n, c) {
  219.             if(n === undefined || n === null || regExp.Blank.test(n)) {
  220.                 throw "The section name must be specified and shouldn't be null.";
  221.                 return undefined;
  222.             } else return {
  223.                 name : n,
  224.                 //为了方便,没有填注释的默认开头换行隔开;如果不要空行,可设置为空字符串 ""
  225.                 comments : c === undefined ? " " : c,
  226.                 parameters : [],
  227.                 getParameterNames : function() {
  228.                         var arr = [];
  229.                         for(var i = 0; i < this.parameters.length; i++) {
  230.                             arr.push(this.parameters[i].name);
  231.                         }
  232.                         return arr;
  233.                     },
  234.                 add : function(p, v, c) {
  235.                         this.parameters.addObject(Parameter, p, v, c);
  236.                         return this;
  237.                     },
  238.                 get : function(paramName) {
  239.                         return this.parameters.getObject(paramName);
  240.                     },
  241.                 remove : function(paramName) {
  242.                         return this.parameters.removeObject(paramName);
  243.                     },
  244.                 sort : function(isAscOrDesc) {
  245.                         this.parameters.sortObject(isAscOrDesc);
  246.                         return this;
  247.                     },
  248.                 toString : function() {
  249.                         var s = parseCommentLines(this.comments);
  250.                         s += "[" + this.name + "]";
  251.                         for(var i = 0; i < this.parameters.length; i++) {
  252.                             s = s + "\r\n" + this.parameters[i].toString();
  253.                         }
  254.                         //每节最后都有换行
  255.                         return s + "\r\n";
  256.                     }
  257.             }
  258.         };
  259.    
  260.    
  261.     /*****************************************
  262.                   加载文件内容
  263.      *****************************************/
  264.     if(iniFileName && iniFileName.length > 0) {
  265.         var fso = new ActiveXObject("Scripting.FileSystemObject");
  266.         if(!fso.FileExists(iniFileName)) {
  267.             throw "File not found:\r\n" + iniFileName;
  268.             return;
  269.         } else {
  270.             var f = fso.OpenTextFile(iniFileName, 1);
  271.             var currComments, currSection;
  272.             while(!f.AtEndOfStream) {
  273.                 var strLine = f.ReadLine();
  274.                 if(regExp.Blank.test(strLine)) {
  275.                     if(currComments) {
  276.                         //文件注释:从文件开头以来第一段连续的注释
  277.                         if(this.comments === undefined && regExp.NonBlank.test(currComments)) {
  278.                             this.comments = currComments;
  279.                             currComments = null;
  280.                         } else {
  281.                             currComments += " \r\n";
  282.                         }
  283.                     } else {
  284.                         currComments = " ";
  285.                     }
  286.                 } else if(regExp.Comment.test(strLine)) {
  287.                     var commentLine = strLine.replace(regExp.Comment, "$1");
  288.                     if(currComments) {
  289.                         currComments += "\r\n" + commentLine;
  290.                     } else {
  291.                         currComments = commentLine;
  292.                     }
  293.                 } else if(regExp.Section.test(strLine)) {
  294.                     //没有文件注释
  295.                     if(this.comments === undefined) {
  296.                         this.comments = "";
  297.                     }
  298.                     var currSecName = strLine.replace(regExp.Section, "$1");
  299.                     this.add(currSecName, currComments);
  300.                     currSection = this.get(currSecName);
  301.                     currComments = null;
  302.                 } else if(regExp.Parameter.test(strLine)) {
  303.                     if(!currSection) {
  304.                         throw "File format error. Section name must be the first, not a parameter.";
  305.                         break;
  306.                     }
  307.                     var currParamName  = strLine.replace(regExp.Parameter, "$1");
  308.                     var currParamValue = strLine.replace(regExp.Parameter, "$2");
  309.                     currSection.add(currParamName, currParamValue, currComments);
  310.                     currComments = null;
  311.                 } else {
  312.                     throw "File format error. Couldn't parse :\r\n" + strLine;
  313.                     break;
  314.                 }
  315.             }
  316.             f.Close();
  317.             fileName = iniFileName;
  318.         }
  319.     } else {
  320.         //不从文件读,则赋值,以免toString出错
  321.         this.comments = "";
  322.     }
  323.    
  324.     //It's better to be initalized by "new IniObject(fn)"
  325.     //return this;
  326. };
复制代码
1

评分人数

返回列表