Node.js入门教程 第三篇 (模块、路由)

Node.js的模块

Node.js的模块与传统面向对象的类(class)不完全相同。Node.js认为文件即模块,即一个文件是一个模块。单一文件一般只专注做一件事情,保证了代码的简洁性。

创建模块:

 //test.js
 exports.world = function() {
   console.log('Hello World');
 }

引用模块(Node.js默认文件名后缀为.js):

 var hello = require('./test'); 
 hello.world(); 

创建模块时,我们需要向外侧暴漏对象。只有暴漏了对象,外界才可以引用,否则模块不能起到应有的作用,一般暴漏对象有两种方式:

1、exports.[function name]= [function name]

2、moudle.exports= [function name]

 

两者的区别是,前者暴漏的是模块的函数(即方法),后者暴漏的是一个完整的模块对象(即类)。例如上文的 exports.world 只是暴漏了一个函数world。

接下来使用 moudle.exports 来暴漏一个完整的模块对象:

 //test.js 
 function Hello() { 
     var name; 
     this.setName = function(thyName) { 
         name = thyName; 
     }; 
     this.sayHello = function() { 
         console.log('Hello ' + name); 
     }; 
}; 
module.exports = Hello;

使用模块:

 var Hello = require('./test'); 
 hello = new Hello(); //由于引用的是一个对象,所以需要new
 hello.setName('XXX'); 
 hello.sayHello(); 

 

Node.js的路由


路由是指为目标分配对应的路径指向(向导作用)。在Node.js中,路由可以简单的理解为给访问对象分配对应的路径。

例如,在url中访问http://127.0.0.1:8080/home,我们需要在服务端为其指向对应的home文件路径。

 

我们先写出home界面文件:

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>Document</title>
 </head>
 <body>
 home
 </body>
 </html>

在服务端写出路由:

let http = require('http');
let url = require('url');
let fs = require('fs');
http.createServer(function(req,res){
    let pathname = url.parse(req.url).pathname;
    console.log('Request for ' + pathname + ' received.');
    function showPaper(path,status){
        let content = fs.readFileSync(path);
        res.writeHead(status, { 'Content-Type': 'text/html;charset=utf-8' });
        res.write(content);
        res.end();
    }
    //分配路由
    switch(pathname){
        case '/home':
            showPaper('./home.html',200);
            break;
    }
}).listen(8080);

 

这样,当访问http://127.0.0.1:8080/home时,路由将会加载home.html。

 

路由的分配并不复杂,但是很繁琐。现有的Node.js技术中express框架已经实现并简化了路由功能,在后续会专门讲解express框架

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值