zoukankan      html  css  js  c++  java
  • Node.js入门教程 第三篇 (模块、路由)

    Node.js的模块

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

    创建模块:

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

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

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

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

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

    2、moudle.exports= [function name]

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

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

     1 //test.js 
     2 function Hello() { 
     3     var name; 
     4     this.setName = function(thyName) { 
     5         name = thyName; 
     6     }; 
     7     this.sayHello = function() { 
     8         console.log('Hello ' + name); 
     9     }; 
    10 }; 
    11 module.exports = Hello;

    使用模块:

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

    Node.js的路由

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

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

    我们先写出home界面文件:

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Document</title>
     6 </head>
     7 <body>
     8 home
     9 </body>
    10 </html>

    在服务端写出路由:

     1 let http = require('http');
     2 let url = require('url');
     3 let fs = require('fs');
     4 http.createServer(function(req,res){
     5     let pathname = url.parse(req.url).pathname;
     6     console.log('Request for ' + pathname + ' received.');
     7     function showPaper(path,status){
     8         let content = fs.readFileSync(path);
     9         res.writeHead(status, { 'Content-Type': 'text/html;charset=utf-8' });
    10         res.write(content);
    11         res.end();
    12     }
    13     //分配路由
    14     switch(pathname){
    15         case '/home':
    16             showPaper('./home.html',200);
    17             break;
    18     }
    19 }).listen(8080);

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

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

  • 相关阅读:
    最近这段时间
    一元多项式的
    珍藏
    运行命令大全
    Google
    Windows Live Writer插件
    Word写论文的技
    安装Windows Live Writer后Ƃ
    比尔盖茨给人
    不经意的感悟
  • 原文地址:https://www.cnblogs.com/JHelius/p/11645838.html
Copyright © 2011-2022 走看看