设为首页 收藏本站
查看: 1096|回复: 0

[经验分享] NodeJS测试实例

[复制链接]

尚未签到

发表于 2017-2-24 10:31:05 | 显示全部楼层 |阅读模式
  实例一:
  先来个简单的实例,把下面的代码保存为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\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,就可以到熟悉的内容了。
  ======================================================================
  实例二:
  通过读去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\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,就可以到熟悉的内容了。
  ======================================================================
  实例三:
  读写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,就可以到熟悉的内容了。
  ======================================================================
  ======================================================================

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-346526-1-1.html 上篇帖子: Nodejs与ES6系列3:generator对象 下篇帖子: Nodejs进阶:核心模块net入门与实例讲解
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表