持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情
今天来学习服务器端模块化的相关知识,并简单创建一个基础的 Node.js 应用
服务器端模块化
服务器端的模块化规范:CommonJS (规定了模块的特性和各模块之间如何相互依赖,Node.js遵循该模块化规范)
在Node环境中,一个js文件就是一个模块(module),模块内部的成员都是相互独立。
a. 模块化的优点
- 提高了代码的可维护性,当一个模块编写完毕,就可以在代码中实现复用
- 避免函数名和变量名冲突
b. 模块导出与引入
如果要导出单个的成员或者比较少的成员,一般使用
exports导出;
如果要导出的成员比较多,一般使用module.exports的方式。(这两种方式不能同时使用 )exports与module的关系:
module.exports = exports = {};
require()加载模块,默认返回一个对象
var sum = function(a,b){
return parseInt(a) + parseInt(b);
}
// 导出模块成员
exports.sum = sum;
// 导出成员的另一种方式(输出的可以是任意对象、函数、数组等)
module.exports = function(){
console.log('hello');
};
//引入模块
var module = require('./03.js');
c. 模块分类
- 自定义模块(文件模块)
- 用户创建的每个 .js(.json、.node) 文件,都是自定义模块。
- 文件模块可以分为:.js模块、 .json模块、 .node模块
- 文件模块查找顺序
上述三种文件模块的加载优先级(指定的模块文件没有文件后缀时的优先级):.js -> .json -> .node
- 系统核心模块(nodejs 官方提供的)
fs文件操作http网络操作path路径操作querystring查询参数解析urlurl解析
d. 简单运用
(1)在之前的系列文章的hello.js文件中,创建一个函数,并导出该函数
'use strict';
function hello() {
console.log('Hello, world!');
}
module.exports = {
hello,
};
(2)创建一个main.js文件,引入hello文件模块,并调用hello.js中写的函数
'use strict';
var obj = require('./hello');
obj.hello();
(3)执行node main.js命令,就可以得到hello.js中输出的内容
搭建一个基础的HTTP服务器
require()引入Node.js自带的 http 模块
const http = require('http')
- 创建http服务器:在项目的根目录下创建一个server.js的文件
const http = require('http');
const port = 8080;
const server = http.createServer((request, response) => {
//当收到请求时,使用 response.writeHead() 函数发送一个HTTP状态200(表示响应成功)和HTTP头的内容类型(content-type)
response.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"});
//使用 response.write() 函数在HTTP相应主体中发送文本“Hello World"。
response.write("Hello World");
//调用 response.end() 完成响应
response.end();
})
//设置服务器端口并进行监听
server.listen(port, () => { console.log(`服务器运行在 http://localhost:${port}/`) })
- 执行命令
node server.js运行server.js文件,Ctrl+ 单击运行网址,会看到一个写着“Hello World”的网页