Node.js入门教程 第三篇 (模块及路由)
2024-08-27 07:30:28
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框架。
最新文章
- WiFi QC 自动测试:ixChariot API初探
- SD卡读写一些函数
- ASP.NET MVC5 实现网址伪静态
- MVC执行过程
- 一个C#语法高亮插件
- python 正则,常用正则表达式大全
- ionic build android-->; Build failed with an exception. Execution failed for task &#39;:processDebugResources&#39;.
- [Architecture Design] CLK Architecture
- Google将数十亿行代码储存在单一的源码库
- vim file save as
- Lifting the Stone(hdoj1115)
- SQL Server 判断表中是否存在某字段
- 运行计划之误区,为什么COST非常小,SQL却跑得非常慢?
- VS多平台开发
- PHP 单态设计模式复习
- python之二维码生成
- SpriteBuilder中音频波长超过Timeline结尾的情况
- SQL Server 中执行Shell脚本计算本地文件的内容大小
- 全志A33移植LCD驱动(ILI9806E)
- POJ 2299
热门文章
- jquery中的 $(function(){ .. }) 函数
- 运维核心基础知识之——MD5sum校验文件
- JSP标签介绍
- C# Post Get 方式发送请求
- Spotlight on Oracle注册码破解(亲测可用)
- android 解决 多品牌手机拍照问题,尤其是小米手机
- airflow + CeleryExecutor 环境搭建
- 【学习笔记】python3核心技术与实践--如何逐步突破,成为python高手
- Mysql优化总结(一)
- zookeeper伪集群