Node.js—学习
一、Node.js
1. Hello World
var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
if(request.url!=="/favicon.ico"){ //清除第2此访问
console.log('访问');
response.write('hello,world');
response.end('hell,世界');//不写则没有http协议尾,但写了会产生两次访问
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
/*
启动服务
cmd下执行:
node n1_hello.js
浏览器访问:http://localhost:8000
*/
2. 函数调用
//---服务器node.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此访问
fun1(response);
otherfun.controller(request,response);
otherfun.call(response);
//---使用字符串调用对应的函数---
funcname = "addContent"
otherfun[funcname](response);
otherfun['getVisit'](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++;
},
addContent:function(a,b){
return a+b;
}
}
3. 模块调用
//---node.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对象
teacher = new Teacher(1,'李四',30);
teacher.teach(response);
response.end('');
}
}).listen(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;
4. 路由
//---node.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"){
//获取url的路径
var pathname = url.parse(request.url).pathname;
//替换掉路径前面的 /
pathname = pathname.replace(/\//,'');
router[pathname](request,response);
response.end('');
}
}).listen(8000);
//---router.js---
module.exports={
login:function(req,res){
res.write("我是login方法");
},
zhuce:function(req,res){
res.write("我是注册方法");
}
}
5. 文件读取
//---node.js---
var http = require("http");
var optfile = require("./models/optfile");
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/html';charset=utf-8'});
if(request.url!=="/favicon.ico"){
//闭包函数;防止异步操作时,已经end了,再进行write报错
function recall(data){
response.write(data);
response.end('ok')
}
optfile.readfile('./views/login.html',recall);
console.log('主程序执行完毕');
}
}).listen(8000)
//---/models/optfile---
var fs = require('fs');
module.exports={
//同步读取
readfileSync:function(path){
var data = fs.readFileSync(path,'utf-8');
console.log("同步方法执行完毕");
return data;
},
//异步读取
readfile:function(path,recall){
fs.readFile(path,function(err,data){
if(err){
console.log(err);
}else{
console.log(data.toString());
recall(data);
}
})
}
}
//---修改后路由---
//---node.js---
var http = require('http');
var url = require('url');
var router = require('./router');
var optfile = require("./models/optfile");
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/html';charset=utf-8'});
if(request.url!=="/favicon.ico"){
//获取url的路径
var pathname = url.parse(request.url).pathname;
//替换掉路径前面的 /
pathname = pathname.replace(/\//,'');
router[pathname](request,response);
console.log('主程序执行完毕');
}
}).listen(8000)
//---router.js---
var optfile = require("./models/optfile");
module.exports={
login:function(req,res){
function recall(data){
res.write(data);
res.end("");
}
optfile.readfile('./views/login.html',recall);
},
zhuce:function(req,res){
function recall(data){
res.write(data);
res.end("");
}
optfile.readfile('./views/zhuce.html',recall);
}
}
6. 文件写入
//---node.js---
var http = require('http');
var url = require('url');
var router = require('./router');
var optfile = require("./models/optfile");
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/html';charset=utf-8'});
if(request.url!=="/favicon.ico"){
//获取url的路径
var pathname = url.parse(request.url).pathname;
//替换掉路径前面的 /
pathname = pathname.replace(/\//,'');
router[pathname](request,response);
console.log('主程序执行完毕');
}
}).listen(8000)
//---/models/optfile---
var fs = require('fs');
module.exports={
//同步写入
writefileSync:function(path,data){
fs.writeFileSync(path,data);
console.log("同步方法执行完毕");
},
//异步读取
writefile:function(path,data,recall){
fs.writeFile(path,data,function(err){
if(err){
throw err;
}else{
console.log("It is saved!");
recall('写文件成功')
}
})
}
}
//---router.js---
var optfile = require("./models/optfile");
module.exports={
login:function(req,res){
function recall(data){
res.write(data);
res.end("");
}
optfile.readfile('./views/login.html');
},
writefile:function(req,res){
function recall(data){
res.write(data);
res.end("");
}
optfile.writefile('./views/one.txt','hello world',recall);
}
}
7. 读取图片
//---node.js---
var http = requrie('http');
var optfile = require('./models/optfile');
http.createServer(function(request,response){
//读取图片需要时二进制流格式
response.writeHead(200,{'Content-Type':'image/jpeg'});
if(request.url!='/favicon.ico'){
optfile.readImg('./imgs/pig.png',response);
}
}).listen(8000);
//---/models/optfile---
var fs = require('fs');
module.exports={
readImg:function(path,res){
//默认为string,binary是二进制
fs.readFile(path,'binary',function(err,filedata){
if(err){
console.log(err);
return;
}else{
res.write(filedata,'binary');
res.end();
}
})
}
}
8. 异常处理
//同步捕获异常
pathname = url.parse(request.url).pathname;
pathname = pathname.replace(/\//,'');
try{
router[pathname](request,response);
}catch(err){
console.log("error="+err);
response.writeHead(200,{'Content-Type':'text/html';charset='utf-8'});
response.write(err.toString());
response.end('');
}
//---node.js---
var http = require('http');
var url = require('url');
var router = require('./router');
var exception = require('./models/Exception');
http.createServer(function (request,response){
if(request.url!=="/favicon.ico"){//清除第2此访问
pathname=url.parse(request.url).pathname;
pathname = pathname.replace(/\//,'');//替换掉前面的/
try{
//router[pathname](request,response);
data = exception.expfun(0);
response.write(data);
response.end('');
}catch(err){
console.log('aaaaa='+err);
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
response.write(err.toString());
response.end('');
}
console.log("server执行完毕");
}
}).listen(8000);
//---Exception.js---
module.exports={
expfun:function(flag){
if(flag==0){
//抛出异常
throw '我是例外';
}
return "success";
}
}
9. 参数接收
<form action='./login' method='get'>
<input type='text' name='email'/>
<input type='password' name='pwd'/>
<input type='submit' value='登录'>
</form>
//---node.js---
var http = require('http');
var url = require('url');
var router = require('./router');
http.createServer(function(request,response){
if(request.url!=="/favicon.ico"){ //清除第2此访问
pathname=url.parse(request.url).pathname;
pathname = pathname.replace(/\//,'');//替换掉前面的/
try{
router[pathname](request,response);
}catch(err){
console.log('出错='+err);
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
response.write(err);
response.end('');
}
console.log("server执行完毕");
}
}).listen(8000);
//---router.js--
var optfile = require('./models/optfile');
var url = require('url');
var querystring = require('querystring'); //post需导入
module.exports={
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的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
req.on('data', function(chunk){
post += chunk;
});
//-------注意异步-------------
//在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
req.on('end', function(){
post = querystring.parse(post);
console.log('email:'+post['email']+'\n');
console.log('pwd:'+post['pwd']+'\n');
});
//---------------------------------------
data = optfile.readfileSync('./views/login.html');
res.write(data);
res.end();
}
}
Node.js—学习的更多相关文章
- NODE.JS学习的常见误区及四大名著
NODE.JS学习的常见误区及四大名著 前段时间由于不满于社区里很多人对于NODE.JS的种种误解而写了一篇文章名为: NODE.JS之我见:http://www.cnblogs.com/pugang ...
- Node.js学习系列总索引
Node.js学习系列也积累了一些了,建个总索引方便相互交流学习,后面会持续更新^_^! 尽量写些和实战相关的,不讲太多大道理... Node.js学习笔记系列总索引 Nodejs学习笔记(一)--- ...
- 【入门必备】最佳的 Node.js 学习教程和资料书籍
Web 开发人员对 Node.js 的关注日益增多,更多的公司和开发者开始尝试使用 Node.js 来实现一些对实时性要求高,I/O密集型的业务.这篇文章中,我们整理了一批优秀的资源,你可以得到所有你 ...
- node.js学习(1)
新建便笺 3 node.js学习(1) 1)安装 http://nodejs.org/download/下载. 2)编写一个案例 var http=require("http"); ...
- 我的Node.js学习历程
学习一门技术,每个人都有每个人的方法.我的方法很简单,做项目. 基本概念 在搭建一个node网站之前,还是要掌握一些基本的概念的,这里列举一下,具体的内容大家自己到网上去查: npm bower ex ...
- Node.js学习之TCP/IP数据通讯
Node.js学习之TCP/IP数据通讯 1.使用net模块实现基于TCP的数据通讯 提供了一个net模块,专用于实现TCP服务器与TCP客户端之间的通信 1.1创建TCP服务器 在Node.js利用 ...
- Node.js学习起步
Node.js学习: 简单的说 Node.js 就是运行在服务端的 JavaScript.Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台.Node.js是一个事件驱 ...
- 一点感悟:《Node.js学习笔记》star数突破1000+
写作背景 笔者前年开始撰写的<Node.js学习笔记> github star 数突破了1000,算是个里程碑吧. 从第一次提交(2016.11.03)到现在,1年半过去了.突然有些感慨, ...
- Node.js学习看这里:基础、进阶、文章
Node.js是基于Chrome JavaScript运行时建立的一个平台,实际上它是对Google Chrome V8引擎进行了封装,它主要用于创建快速的.可扩展的网络应用. Node.js采用事件 ...
- Node.js学习笔记(3):NPM简明教程
Node.js学习笔记(3):NPM简明教程 NPM常用操作 更新NPM版本 npm install npm -g -g,表示全局安装.我们可以指定更新版本,只需要在后面填上@版本号即可,也可以输入@ ...
随机推荐
- c# 获取sqlserver 运行脚本的print消息的方法分享
转自:http://www.maomao365.com/?p=6923 摘要: 在sql脚本的编写中,我们经常使用sql脚本print消息,作为输出测试, 通过获取print消息,我们可以快速获取程 ...
- cf 【并查集】
http://codeforces.com/contest/1245/problem/D 题意就是:你需要让所有城市都有电,你看也在该城市建电站使他有电,同时你可以链接他与其他城市,使之有电 解决: ...
- SpringCloud单元测试【六】
SpringCloud的单元测试主要是依靠 Mock以及Mockito, 所以我们需要对Mock以及Mockito有一定的认识. 一.为什么要用MockMvc 可能我们在测试控制层的代码都是启动服务器 ...
- javascript中的闭包、函数的toString方法
闭包: 闭包可以理解为定义在一个函数内部的函数, 函数A内部定义了函数B, 函数B有访问函数A内部变量的权力: 闭包是函数和子函数之间的桥梁: 举个例子: let func = function() ...
- Protractor - 环境设置
去年出于好奇搭建过一个Protractor+Cucumber的测试框架,当时项目上并没有用到AngularJS,所以框架能运行起来之后没有再深入了.最近新项目引入了AngularJS,想起去年搭的那个 ...
- Java-100天知识进阶-Java内存-知识铺(四)
知识铺: 致力于打造轻知识点,持续更新每次的知识点较少,阅读不累.不占太多时间,不停的来唤醒你记忆深处的知识点. 1.Java内存模型是每个java程序员必须掌握理解的 2.Java内存模型的主要目标 ...
- rpmrebuild 下载安装
下载 https://jaist.dl.sourceforge.net/project/rpmrebuild/rpmrebuild/2.14/rpmrebuild-2.14.tar.gz 安装 将其做 ...
- linux服务器上配置进行kaggle比赛的深度学习tensorflow keras环境详细教程
本文首发于个人博客https://kezunlin.me/post/6b505d27/,欢迎阅读最新内容! full guide tutorial to install and configure d ...
- MySQL for OPS 09:MHA + Atlas 实现读写分离高可用
写在前面的话 前面做了 MHA 高可用,但是存在这样一个问题,我们花了 4 台机器,但是最终被利用起来的也就一台,主库.这样硬件利用率才 25%,这意味着除非发生故障,不然其他几台机器都是摆设.明显的 ...
- node-sass安装失败处理办法
参考: https://npm.taobao.org/mirrors https://lzw.me/a/node-sass-install-helper.html 设置环境变量安装 SASS_BINA ...