http
'use strict';
// 导入http模块:
var http = require('http');
// 创建http server,并传入回调函数:
var server = http.createServer(function (request, response) {
// 回调函数接收request和response对象,
// 获得HTTP请求的method和url:
console.log(request.method + ': ' + request.url);
if(request.url!=="favicon.ico"){//清除第2次访问,在Express框架里已经实现过了
// 将HTTP响应200写入response, 同时设置Content-Type: text/html:
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('I am coming!');
// 将HTTP响应的HTML内容写入response:
response.end('<h1>Hello world!</h1>');//结束访问
}
});
// 让服务器监听8080端口:
server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');```
函数调用
本地函数
//--------------------n2_funcall.js---------------------------------
var http = require('http');
var otherfun = require('./models/otherfuns.js');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){ //清除第2此访问
otherfun.controller(request,response); //等同于otherfun['controller'](request,response)
otherfun.call(response);
//以下是很重要的调用方式(用函数名的字符串调用)
funname = 'fun3';
otherfun[funname](response);
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//---普通函数
function fun1(res){ //本地函数,直接调用
res.write("你好,我是fun1");
}
其他文件的函数(包括单一函数调用和多函数调用)
//-------------------models/otherfuns.js--------------------------
function controller(req,res){
//res.write("发送");
call('hello',req,res);
res.end("");
}
function call(res){
console.log('call');
}
module.exports = controller; //只支持一个函数
/*
//支持多个函数
module.exports={
getVisit:function(){
return visitnum++;
},
add:function(a,b){
return a+b;
}
}
*/
模块调用
//----------------------main.js-------------
var http = require('http');
//var User = require('./models/User');
var Teacher = require('./models/Teacher');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){ //清除第2此访问
teacher = new Teacher(1,'李四',30);
teacher.teach(response);//写在网页上
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//--------------User.js-------------- 父类
function User(id,name,age){
this.id=id;
this.name=name;
this.age=age;
this.enter=function(){
console.log("进入图书馆");//打印在后台
}
}
module.exports = User;
//-------------------models/Teacher.js--------- 子类
var User = require('./User');
function Teacher(id,name,age){
User.apply(this,[id,name,age]);//继承
this.teach=function(res){
res.write(this.name+"老师讲课");//写在网页上
}
}
module.exports = Teacher;
路由
//---------main.js-----------
var http = require('http');
var url = require('url');
var router = require('./router');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){
var pathname = url.parse(request.url).pathname;//得到浏览器输入的路径
//输入http://127.0.0.1:8000/login,得到/login
pathname = pathname.replace(/\//, '');//替换掉前面的/
router[pathname](request,response);
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//-----------------router.js--------------------------------
module.exports={//两个子页面
login:function(req,res){
res.write("我是login方法");
},
zhuce:function(req,res){
res.write("我是注册方法");
}
}
读文件
大部分都使用异步读文件
//-----------main.js-------------------------
var http = require('http');
var optfile = require("./optfile");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){ //清除第2此访问
//optfile.readfileSync('./views/login.html')
function racall(data){//闭包函数,可以使用其完成任务再结束访问
response.write(data);
response.end('ok');
}
optfile.readfile('./views/login.html', racall);//访问界面
//response.end('ok');
console.log('主程序执行完毕')
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//-------------optfile.js-------------------------
var fs = require('fs');
module.exports={
readfile:function(path, recall){
fs.readFile(path, function(err, data){// 异步执行
if(err){
console.log(err);
}
else{
console.log(data.toString());
recall(data);
}
});
console.log("异步方法执行完毕");
},
readfileSync:function(path){//同步执行
var data = fs.readFileSync(path, 'utf-8');
console.log(data);
console.log("同步方法执行完毕");
return data;
}
}
//-------------views/login.html-------------------------
登录界面
通过路由读文件
只能访问http://127.0.0.1:8000/login和http://127.0.0.1:8000/zhuce两个界面。
//-----------main.js-------------------------
var http = require('http');
var url = require("url");
var router = require("./router")
//var optfile = require("./optfile");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){
var pathname = url.parse(request.url).pathname;//得到浏览器输入的路径
//输入http://127.0.0.1:8000/login,得到/login
pathname = pathname.replace(/\//, '');//替换掉前面的/
router[pathname](request,response);
}
console.log('主程序执行完毕');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//-------------optfile.js-------------------------
var fs = require('fs');
module.exports={
readfile:function(path, recall){
fs.readFile(path, function(err, data){
if(err){
console.log(err);
}
else{
console.log(data.toString());
recall(data);
}
});
console.log("异步方法执行完毕");
},
readfileSync:function(path){
var data = fs.readFileSync(path, 'utf-8');
console.log(data);
console.log("同步方法执行完毕");
return data;
}
}
//-----------------router.js--------------------------------
var optfile = require("./optfile");
module.exports={
login:function(req,res){
function recall(data){
res.write(data);
res.end('ok');
}
optfile.readfile('./views/login.html', recall);
//res.write("我是login方法");
},
zhuce:function(req,res){
function recall(data){
res.write(data);
res.end('ok');
}
optfile.readfile('./views/zhuce.html', recall);
//res.write("我是注册方法");
}
}
//-----------------login.html--------------------------------
登录界面
//-----------------zhuce.html--------------------------------
注册界面
写文件
//-----------main.js-------------------------
主文件同上
//-------------optfile.js-------------------------
var fs = require('fs');
module.exports={
writefile:function(path,data, recall){ //异步方式
fs.writeFile(path, data, function (err) {
if (err) {
throw err;
}
console.log('It\'s saved!'); //文件被保存
recall('写文件成功');
});
},
writeFileSync:function(path,data){ //同步方式
fs.writeFileSync(path, data);
console.log("同步写文件完成");
}
}
//-----------------router.js--------------------------------
var optfile = require("./optfile");
module.exports={
writefile:function(req, res){
function recall(data){
res.write(data);
res.end('ok');
}
optfile.writefile('./views/file0.txt', '我是写入文件', recall);
}
}
读取图片
//-----------main.js-------------------------
var http = require('http');
var optfile = require("./optfile");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type':'image/jpeg'});
if(request.url!=="/favicon.ico"){ //清除第2此访问
console.log('访问');
//response.write('hello,world');//不能向客户端输出任何字节
optfile.readImg('./image/0.jpg',response);
//------------------------------------------------
console.log("继续执行");
//response.end('hell,世界');//end在方法中写过
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//-------------optfile.js-------------------------
var optfile = require("./optfile");
module.exports={
readImg:function(path, res){
fs.readFile(path, 'binary', function(err, file){//注意'binary'
if(err){
console.log(err);
return;
}
else{
console.log("输出文件");
res.write(file, 'binary');
res.end();
}
})
}
}
路由改造
主要解决页面同时显示文字和图片,即显示一个html页面。
//-----------main.js-------------------------
var http = require('http');
var url = require("url");
var router = require("./router")
var optfile = require("./optfile");
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){
var pathname = url.parse(request.url).pathname;//得到浏览器输入的路径
//输入http://127.0.0.1:8000/login,得到/login
pathname = pathname.replace(/\//, '');//替换掉前面的/
router[pathname](request,response);
}
console.log('主程序执行完毕');
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//-------------optfile.js-------------------------
var fs = require('fs');
module.exports={
readImg:function(path, res){
fs.readFile(path, 'binary', function(err, file){
if(err){
console.log(err);
return;
}
else{
console.log("输出文件");
res.write(file, 'binary');
res.end();
}
})
}
}
//-----------------router.js--------------------------------
var optfile = require("./optfile");
function getRecall(req, res){//闭包函数用于解决异步读取文件
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});//发送
function recall(data){
res.write(data);
res.end('');//结束
}
return recall;
}
module.exports={
login:function(req,res){
recall = getRecall(req, res);
optfile.readfile('./views/login.html', recall);
//res.write("我是login方法");
},
zhuce:function(req,res){
recall = getRecall(req, res);
optfile.readfile('./views/zhuce.html', recall);
//res.write("我是注册方法");
},
writefile:function(req, res){
recall = getRecall(req, res);
optfile.writefile('./views/file0.txt', '我是写入文件', recall);
},
showimg:function(req, res){
res.writeHead(200, {'Content-Type':'image/jpeg'});
optfile.readImg('./image/0.jpg', res);
}
}
//-----------------login.html--------------------------------
<html>
<head>
登录界面
</head>
<body>
欢迎你!
<img src="./showimg"/>
</body>
</html>
以上的逻辑为:输入http://127.0.0.1:8000/login
, main.js解析出login分页面,发送至router.js的login函数,读取’./views/zhuce.html’文件,浏览器解析html文件时,是文字则输出,解析到<img src="./showimg"/>
,main.js解析出showimg,发送至router,js的showimg函数,调用optfile.readImg(’./image/0.jpg’, res),读取出图片。
异常处理
try{
router[pathname](request,response);
/*
data = exception.expfun(0);
response.write(data);
response.end('');
*/
}catch(err){
console.log('aaaa='+err);
response.writeHead(200, {'Content-Type': 'text\html; charset=utf-8'});
response.write(err.toString());
response.end('');
}
fs.readFile(path, function(err, data){
if(err){
console.log(err);
console.log('文件不存在');
recall('文件不存在');
}
else{
console.log(data.toString());
recall(data);
}
});
module.exports = {
expfun:function(flag){
if(flag==0){
throw '我是例外';
}
return 'success';
}
}
提交表单(get和post)
var querystring = require('querystring'); //post需导入
login:function(req,res){
/*
//--------get方式接收参数---------------- 不够安全,且为同步
var rdata = url.parse(req.url,true).query; //得到输入的数据
console.log(rdata);
if(rdata['email']!=undefined){
console.log(rdata['email']); //后台打印
}
*/
//-------post方式接收参数---------------- 异步方式
var post = ''; //定义了一个post变量,用于暂存请求体的信息
req.on('data', function(chunk){ //通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
post += chunk;
});
//-------注意异步-------------
req.on('end', function(){ //在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
post = querystring.parse(post); //到最后一起解析
console.log('email:'+post['email']+'\n');
console.log('pwd:'+post['pwd']+'\n');
});
//---------------------------------------
recall = getRecall(req, res);
optfile.readfile('./views/login.html', recall);
//res.write("我是login方法");
},
//-----------------login.html--------------------------------简单的登录页面
<html>
<head>
登录界面
</head>
<body>
<form action="./login" method="post">
<table align="center">
<tr>
<td>email:</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td align="center"><input type="submit" value="登录"/></td>
</tr>
</table>
</form>
</body>
</html>
动态网页(正则表达式替换)
通过你输入的信息,在网页上显示
login:function(req,res){
//--------get方式接收参数----------------
/*
var rdata = url.parse(req.url,true).query;
console.log(rdata);
if(rdata['email']!=undefined){
console.log(rdata['email']);
console.log(rdata['pwd']);
}
*/
//-------post方式接收参数----------------
var post = '';//定义了一个post变量,用于暂存请求体的信息
req.on('data', function(chunk){ //通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
post += chunk;
});
//-------注意异步-------------
req.on('end', function(){ //在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
post = querystring.parse(post);
//console.log('email:'+post['email']+'\n');
//console.log('pwd:'+post['pwd']+'\n');
//recall = getRecall(req,res);
arr = ['email','pwd'];
function recall(data){
dataStr = data.toString();
for(var i=0;i<arr.length;i++){
re = new RegExp('{'+arr[i]+'}','g'); // /\{name\}/g
dataStr = dataStr.replace(re,post[arr[i]]);
}
res.write(dataStr);
res.end('');//不写则没有http协议尾
}
optfile.readfile('./views/login.html',recall);
});
}
数据库连接
直接连接mysql
//-------mysql.js------------- 直接连接数据库
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'test',
port:'3306'
});
//创建一个connection
connection.connect(function(err){
if(err){
console.log('[query] - :'+err);
return;
}
console.log('[connection connect] succeed!');
});
//----插入
var userAddSql = 'insert into user (uname,pwd) values(?,?)';
var param = ['aaa','aaa'];
connection.query(userAddSql,param,function(err,rs){
if(err){
console.log('insert err:',err.message);
return;
}
console.log('insert success');
});
//执行查询
var userSearchsql = 'select * from user where uid=?';
var params = [1];
connection.query(userSearchsql, params, function(err, rs) {
if (err) {
console.log('[query] - :'+err);
return;
}
for(var i=0;i<rs.length;i++){
console.log('The solution is: ', rs[i].uname);
}
});
//关闭connection
connection.end(function(err){
if(err){
console.log(err.toString());
return;
}
console.log('[connection end] succeed!');
});
通过线程池连接线程池
//-------sql.js----------------------------
var OptPool = require('./OptPool');
var optPool = new OptPool();
var pool = optPool.getPool();
//执行SQL语句
pool.getConnection(function(err, conn){//从连接池中得到一个连接
var userAddSql = 'insert into user (uname,pwd) values(?,?)';
var param = ['eee','eee'];
conn.query(userAddSql,param,function(err,rs){
if(err){
console.log('insert err:',err.message);
return;
}
console.log('insert success');
//conn.release(); //放回连接池
})
//查询
conn.query('SELECT * from user', function(err, rs) {
if (err) {
console.log('[query] - :'+err);
return;
}
for(var i=0;i<rs.length;i++){
console.log(rs[i].uname);
}
conn.release(); //放回连接池
console.log('end sucess!');
});
})
//-------------OptPool.js---------------------------------
var mysql = require('mysql'); //调用MySQL模块
function OptPool(){
this.flag=true; //是否连接过
this.pool = mysql.createPool({
host: 'localhost', //主机
user: 'root', //MySQL认证用户名
password: 'root', //MySQL认证用户密码
database: 'test',
port: '3306' //端口号
});
this.getPool=function(){
if(this.flag){
//监听connection事件
this.pool.on('connection', function(connection) {
connection.query('SET SESSION auto_increment_increment=1');
this.flag=false;
});
}
return this.pool;
}
};
module.exports = OptPool;
事件处理机制
//-------------main.js------------------------------
var http = require('http');
var events=require("events");
var UserBean = require('./models/UserBean');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
if(request.url!=="/favicon.ico"){
user = new UserBean();
user.eventEmit.once('zhuceSuc',function(uname,pwd){
response.write('注册成功');
console.log('传来uname:'+uname);
console.log('传来pwd:'+pwd);
user.login(request,response);
response.end('');
});//注册监听
user.zhuce(request, response);
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
//----------------UserBean.js-----------------------------
var events=require("events");
var http = require('http');
function UserBean(){
this.eventEmit = new events.EventEmitter();
this.zhuce=function(req,res){
console.log("注册");
req['uname']="aa";
req['pwd']="bb";
this.eventEmit.emit('zhuceSuc','aa','bb'); //抛出事件消息
},
this.login=function(req,res){
console.log("登录");
res.write("用户名:"+req['uname']);
res.write("密码:"+req['pwd']);
res.write("登录");
}
}
module.exports = UserBean;
类似于闭包的逻辑,在main.js中定义了事件eventEmit.once(),先通过user.zhuce(request, response);访问UserBean里的zhuce方法,然后进入eventEmit.once()方法(之前定义了),执行其方法即可。