实例一:

先来个简单的实例,把下面的代码保存为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,就可以到熟悉的内容了。

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

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

NodeJS测试实例的更多相关文章

  1. JMeter学习-026-JMeter 分布式(远程)参数化测试实例

    以前文所述对文章详情的HTTP请求进行性能测试为例.日常实际场景中,不可能所有的人都在同时访问一篇文章,而是多人访问不同的文章,因而需要对文章编号进行参数化,以更好的模拟日常的性能测试场景.同时,因文 ...

  2. webservice测试实例

    webservice测试实例(LR8.1) 接口声明:这个接口是sina的短信服务接口,我只是用来做脚本学习使用,不会对其产生压力:希望读者也只是用来进行录制学习,而不是产生压力. 接口文档:http ...

  3. [原]在Fedora中编译Libevent测试实例

    在我的昨天的博文<[原]我在Windows环境下的首个Libevent测试实例>中介绍了在Windows环境下如何编译一个echo server例子.今天我又试了一下在Linux环境中编译 ...

  4. C++动态链接库测试实例

    前话 上一章节我导出了一个动态链接库 要使用该链接库,我们还需要该链接库对外公开的函数,即头文件 下面开始实例 测试实例 第一步--将动态链接库的dll.lib.和头文件导入项目中 文件目录如下: 项 ...

  5. Linux下简易蜂鸣器驱动代码及测试实例

    驱动代码: #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> ...

  6. 微服务架构 - 离线部署k8s平台并部署测试实例

    一般在公司部署或者真实环境部署k8s平台,很有可能是内网环境,也即意味着是无法连接互联网的环境,这时就需要离线部署k8s平台.在此整理离线部署k8s的步骤,分享给大家,有什么不足之处,欢迎指正. 1. ...

  7. WinForm中 Asp.Net Signalr消息推送测试实例

    p{ text-align:center; } blockquote > p > span{ text-align:center; font-size: 18px; color: #ff0 ...

  8. Confluence 6 从生产环境中恢复一个测试实例

    请参考 Restoring a Test Instance from Production 页面中的内容获得更多完整的说明. 很多 Confluence 的管理员将会使用生产实例运行完整数据和服务的 ...

  9. Rabbit简单测试实例

    Rabbit简单测试实例 安装环境: Yum -y install python-pip Pip install pika 生产者 1 2 3 4 5 6 7 8 9 10 11 import pik ...

随机推荐

  1. php selenium 测试验证码问题

    $this->pause(10000)这段代码用于停止程序执行,可以在这个空隙内输入验证码

  2. 无刷新URL 更新

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  3. Autoprefixer:一个以最好的方式处理浏览器前缀的后处理程序

    Autoprefixer解析CSS文件并且添加浏览器前缀到CSS规则里,使用Can I Use的数据来决定哪些前缀是需要的. 所有你需要做的就是把它添加到你的资源构建工具(例如 Grunt)并且可以完 ...

  4. 设置jvm运行内存

    :1.右击项目—Bulid Path—Configure Build Path—Libraries,找到JRE System Libraary[Sun JDK 1.6.0_13],选中JRE Syst ...

  5. 基于友善之臂ARM-tiny4412--uboot源代码分析

    /* * armboot - Startup Code for OMAP3530/ARM Cortex CPU-core * * Copyright (c) 2004 Texas Instrument ...

  6. JavaScript读书笔记(6)-Function

    Function类型 ECMAScript中函数是对象,每个函数都是Function类型的实例,也有属性和方法,函数是对象,函数名实际上市一个指向函数对象的指针,不会与某个函数绑定: function ...

  7. php html_entity_decode使用总结

    在处理网页字符串的时候,尤其是做爬虫类的应用时,经常会涉及到要处理的字符串中包含html标签,现在对这类字符串的处理做一个小的总结: 有时候获取到的字符串中有html标签,在入库的时候出于安全的考虑通 ...

  8. WebStorm 常用功能

    WebStorm 常用功能的使用技巧分享 WebStorm 是 JetBrain 公司开发的一款 JavaScript IDE,使用非常方便,可以使编写代码过程更加流畅. 本文在这里分享一些常用功能的 ...

  9. erlang中遍历取出某个位置的最大值

    例:有这么一个列表,A = [["abc","bds",3],["ssdss","dddx",2],["sfa ...

  10. @Bean 和@ Component的区别

    @Component auto detects and configures the beans using classpath scanning whereas @Bean explicitly d ...