NodeJS测试实例

实例一:

先来个简单的实例,把下面的代码保存为main.js,让自己欣喜下:

var http = require("http");

function onRequest(request, response){
      console.log("Request received.");
      var str='{"id":"0036",name:"jack",arg:123}';
      response.writeHead(200,{"Content-Type":'text/plain','charset':'utf-8','Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});
      //response.writeHead(200,{"Content-Type":'application/json','Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});
      //response.write("Hello World 8888
");
      response.write(str);
      response.end();
}

http.createServer(onRequest).listen(8888);

console.log("Server has started.port on 8888");

运行方式是在命令行中,直接输入:node main.js,然后打开IE浏览器输入http://127.0.0.1:8888,就可以到熟悉的内容了。

======================================================================

实例二:

通过读去json文件,发送json数据到浏览器,把下面的代码保存为json.js,

var http = require("http");
var fs = require("fs");
var str='{"id":"123",name:"jack",arg:11111}';

function onRequest(request, response){
      console.log("Request received.");
      response.writeHead(200,{"Content-Type":'text/plain','charset':'utf-8','Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});//可以解决跨域的请求
      //response.writeHead(200,{"Content-Type":'application/json',            'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'PUT,POST,GET,DELETE,OPTIONS'});
      //response.write("Hello World 8888
");
      str=fs.readFileSync('data.txt');
      response.write(str);
      response.end();
}

http.createServer(onRequest).listen(8888);

console.log("Server has started.port on 8888
");
console.log("test data: "+str.toString());

然后再相同目录下保存一个data.txt文件,内容为:

{"id":"0036",name:"jack",arg:32100,
remark:"test data"}

运行方式是在命令行中,直接输入:node json.js,然后打开IE浏览器输入http://127.0.0.1:8888,就可以到熟悉的内容了。

======================================================================

实例三:

读写ini文件,首先使用ini文件库,代码如下,保存为ini.js文件

// 参考出处:http://www.oschina.net/code/snippet_81981_24971

var eol = process.platform === "win32" ? "
" : "
"
 
function INI() {
    this.sections = {};
}
 
/**
 * 删除Section
 * @param sectionName
 */
INI.prototype.removeSection = function (sectionName) {
 
    sectionName =  sectionName.replace(/[/g,'(');
    sectionName = sectionName.replace(/]/g,')');
 
    if (this.sections[sectionName]) {
        delete this.sections[sectionName];
    }
}
/**
 * 创建或者得到某个Section
 * @type {Function}
 */
INI.prototype.getOrCreateSection = INI.prototype.section = function (sectionName) {
 
    sectionName =  sectionName.replace(/[/g,'(');
    sectionName = sectionName.replace(/]/g,')');
 
    if (!this.sections[sectionName]) {
        this.sections[sectionName] = {};
    }
    return this.sections[sectionName]
}
 
/**
 * 将INI转换成文本
 *
 * @returns {string}
 */
INI.prototype.encodeToIni = INI.prototype.toString = function encodeIni() {
    var _INI = this;
    var sectionOut = _INI.encodeSection(null, _INI);
    Object.keys(_INI.sections).forEach(function (k, _, __) {
        if (_INI.sections) {
            sectionOut += _INI.encodeSection(k, _INI.sections[k])
        }
    });
    return sectionOut;
}
 
/**
 *
 * @param section
 * @param obj
 * @returns {string}
 */
INI.prototype.encodeSection = function (section, obj) {
    var out = "";
    Object.keys(obj).forEach(function (k, _, __) {
        var val = obj[k];
        if(k=="___comment")return;
        if (val && Array.isArray(val)) {
            val.forEach(function (item) {
                out += safe(k + "[]") + " = " + safe(item) + "
"
            })
        } else if (val && typeof val === "object") {
        } else {
            out += safe(k) + " = " + safe(val) + eol
        }
    })
    if (section && out.length) {
        out = "[" + safe(section) + "]" + eol + out
    }
    if (section || obj.___comment){
        out = obj.___comment + eol + out;
    }
    return out+"
";
}

function safe(val) {
    return (typeof val !== "string" || val.match(/[
]/) || val.match(/^[/) || (val.length > 1 && val.charAt(0) === """ && val.slice(-1) === """) || val !== val.trim()) ? JSON.stringify(val) : val.replace(/;/g, '\;')
}
 
var regex1 = {
    section: /^s*[s*([^]]*)s*]s*$/,
    param: /^s*([w.-\_@]+)s*=s*(.*?)s*$/,
    comment: /^s*;.*$/
};
 
 
var regex = {
    section: /^s*[s*([^]]*)s*]s*$/,
    param: /^s*([w.-\_@]+)s*=s*(.*?)s*$/,
    comment: /^s*[;#].*$/
};
 
 
/**
 * @param data
 * @returns {INI}
 */
exports.parse = function (data) {
    var value = new INI();
    var lines = data.split(/
|
|
/);
    var section = null;
    var comm = null;
    lines.forEach(function (line) {
        if (regex.comment.test(line)) {
            var match = line.match(regex.comment);
            comm = match[0];
            return;
        } else if (regex.param.test(line)) {
            var match = line.match(regex.param);
            if (section) {
                section[match[1]] = match[2];
                if(comm)section[match[1]].___comment=comm;
            } else {
                value[match[1]] = match[2];
                if(comm)value.___comment =comm;
            }
            comm = null;
        } else if (regex.section.test(line)) {
            var match = line.match(regex.section);
            section = value.getOrCreateSection(match[1]);
            if(comm)section.___comment=comm;
            comm = null;
        } else if (line.length == 0 && section) {
            section = null;
            comm = null;
        }
        ;
    });
    return value;
}
 
/**
 * 创建INI
 * @type {Function}
 */
exports.createINI = exports.create = function () {
    return new INI();
};
 
var fs = require('fs');
 
exports.loadFileSync =function(fileName/*,charset*/){
    return exports.parse(fs.readFileSync(fileName, "utf-8")) ;
}

然后创建测试文件iniTest.js文件,

   var INI = require("./INI");//INI模块
   var ini = INI.createINI();//创建一个新的INI
 
   ini.count = 12;//ini文件的Start(没有Section的属性)
 
   //创建一个Section[httpserver]
   var s1 = ini.getOrCreateSection("httpserver");
   s1['host'] = "127.0.0.1";
   s1.port = 8080;
   // 控制台打印
   // count = 12
   //[httpserver]
   //host= 127.0.0.1
   //port= 8080
   console.log("**********************
" + ini);
   var fs = require('fs');
   fs.writeFileSync('f1.ini',ini);//INI 写入 conf.ini
 
   var ini___ = INI.loadFileSync("f1.ini")//从conf.ini读取配置
   console.log("**********************
" + ini___);
   var se = ini___.getOrCreateSection("httpserver");//取得httpserver
   se.root = "/temp";//添加新的属性
   se['host'] ="192.168.1.2";//修改属性
   var new_se = ini___.getOrCreateSection("new se");//添加新的Section
   new_se.test = true;
   console.log("**********************
" + ini___);
   fs.writeFileSync('f1.ini', ini___);//写入文件
   
   ///////////////////////////
   
   ini=INI.loadFileSync("./conf/authz");
   var s2=ini.getOrCreateSection("/");
   console.log("----------------
" + ini);
   s2["@test"]="r";
   //fs.writeFileSync('./conf/authz', ini);
   fs.writeFileSync('f1.ini', ini);
   
   console.log("---------------------------
"+ini)
//   fs.writeFileSync('./conf/authz', ini);
    var ini___ = INI.loadFileSync("f1.ini")//从conf.ini读取配置
    console.log("===========================
" + ini___);

然后我又找了个svn的配置文件,文件名为authz,没有扩展名,内容如下:

#修改authz文件
root=c:系统盘
boot=d:oot

;kkkkkkkk
[/groups]
admin = wzw读写

;this file comment
[/]
@admin = rw

[/trunk/doc]
@dev = rw
@view = r

[/trunk/src]
@dev = rw

 运行方式是在命令行中,直接输入:node iniTest.js,就可以到熟悉的内容了。

======================================================================

======================================================================

原文地址:https://www.cnblogs.com/mq0036/p/5338738.html