nodejs 測試 實例 简体版
原文   原文鏈接

實例一:node

先來個簡單的實例,把下面的代碼保存爲main.js,讓本身欣喜下:json

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\n");
      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,就能夠到熟悉的內容了。跨域

======================================================================瀏覽器

實例二:app

經過讀去json文件,發送json數據到瀏覽器,把下面的代碼保存爲json.js,svn

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\n");
      str=fs.readFileSync('data.txt');
      response.write(str);
      response.end();
}

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

console.log("Server has started.port on 8888\n");
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,就能夠到熟悉的內容了。ui

======================================================================this

實例三:spa

讀寫ini文件,首先使用ini文件庫,代碼以下,保存爲ini.js文件

// 參考出處:http://www.oschina.net/code/snippet_81981_24971

var eol = process.platform === "win32" ? "\r\n" : "\n"
 
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) + "\n"
            })
        } 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+"\n";
}

function safe(val) {
    return (typeof val !== "string" || val.match(/[\r\n]/) || 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(/\r\n|\r|\n/);
    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("**********************\n" + ini);
   var fs = require('fs');
   fs.writeFileSync('f1.ini',ini);//INI 寫入 conf.ini
 
   var ini___ = INI.loadFileSync("f1.ini")//從conf.ini讀取配置
   console.log("**********************\n" + 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("**********************\n" + ini___);
   fs.writeFileSync('f1.ini', ini___);//寫入文件
   
   ///////////////////////////
   
   ini=INI.loadFileSync("./conf/authz");
   var s2=ini.getOrCreateSection("/");
   console.log("----------------\n" + ini);
   s2["@test"]="r";
   //fs.writeFileSync('./conf/authz', ini);
   fs.writeFileSync('f1.ini', ini);
   
   console.log("---------------------------\n"+ini)
//   fs.writeFileSync('./conf/authz', ini);
    var ini___ = INI.loadFileSync("f1.ini")//從conf.ini讀取配置
    console.log("===========================\n" + ini___);

而後我又找了個svn的配置文件,文件名爲authz,沒有擴展名,內容以下:

#修改authz文件
root=c:\系統盤
boot=d:\boot\

;kkkkkkkk
[/groups]
admin = wzw讀寫

;this file comment
[/]
@admin = rw

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

[/trunk/src]
@dev = rw

 運行方式是在命令行中,直接輸入:node iniTest.js,就能夠到熟悉的內容了。

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

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

相關文章
相關標籤/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公眾號
   歡迎關注本站公眾號,獲取更多信息