模块很类似于Java中的类,也是可以继承的,有自己的变量和方法
nj_dome.js
var http = require(‘http‘); var User = require("./model/User");//导入user的模块 var Teacher = require("./model/Teacher");//导入teacher的模块 http.createServer(function (request, response) { response.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘}); if(request.url!=="/favicon.ico"){ /*user = new User(1,"张三",20);//创建一个user并调用方法 user.enter();*/ teacher = new Teacher(2,"李老师",30);//创建一个teacher teacher.enter(); 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(this.name + "进入图书馆"); } } module.exports = User;
teacher.js继承了User的模块
var User = require("./User"); function Teacher(id,name,age){ User.apply(this,[id,name,age]);//继承user模块 this.teach=function(res){//新建自己的方法 res.write(this.name+"讲课"); } } module.exports = Teacher;
-----------------------------------------------------------------------------------------------------------------------------------
读取路由中的方法获取字符串,利用字符串找对应的函数
如http://localhost:8000/login获取login 然后找对应的login函数
nj_router.js
var http = require(‘http‘); var url = require(‘url‘);//node自带的URL var router = require(‘./model/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;//获取路径名称 pathname = pathname.replace(/\//,""); //正则去掉/ console.log(pathname); 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("我是注册方法"); } }