Node.js

作者: 恩德_b0c2 | 来源:发表于2017-06-25 21:08 被阅读0次

模块
Node.js 提供了exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。
接下来我们就来创建hello.js文件,代码如下:

exports.world = function() {
console.log('Hello World');
}
在以上示例中,hello.js 通过 exports 对象把 world 作为模块的访问接口,在 main.js 中通过 require('./hello') 加载这个模块,然后就可以直接访 问main.js 中 exports 对象的成员函数了。

require方法接受以下几种参数的传递:

http、fs、path等,原生模块。
./mod或../mod,相对路径的文件模块。
/pathtomodule/mod,绝对路径的文件模块。
mod,非原生模块的文件模块。
我们以计算圆的周长和面积的两个方法为例:

var PI = Math.PI;
exports.area = function (r) {
return PIrr;
};//exports 是对象,向外提供了area方法接口

exports.circumference = function (r) {
return 2PIr;
};
以上保存为circle.js,下方通过require调用模块:

var circle = require("./circle.js");//require通过引入模块文件,找到exports对象提供的接口
console.log("The area of a circle of radius 4 is " + circle.area(4));
编写稍大一点的程序时一般都会将代码模块化。在NodeJS中,一般将代码合理拆分到不同的JS文件中,每一个文件就是一个模块,而文件路径就是模块名。

在编写每个模块时,都有require、exports、module三个预先定义好的变量可供使用。
模块名可使用相对路径(以./开头),或者是绝对路径(以/或C:之类的盘符开头)。另外,模块名中的.js扩展名可以省略。

模块化的优缺点:
a>优点:
可维护性
1.灵活架构,焦点分离
2.方便模块间组合、分解
3.方便单个模块功能调试、升级
4.多人协作互不干扰
可测试性
1.可分单元测试

b>缺点:
性能损耗
1.系统分层,调用链会很长
2.模块间通信,模块间发送消息会很耗性能
Node.js常用模块和组件
包管理 Package Management: NPM
框架 Framework: ExpressJS
模板 Template: Jade
中间件 Middleware: Connect
WebSocket: Socket.io
数据库 Database: Mongo DB (选了个自己喜欢的)
Mongoose (as a MongoDB ORM)
调错 Debugging: Node Inspector
测试 Test: Mocha + should.js
控制无止境的内嵌回调 (Control the Callback flow): Async

相关文章

  • nodejs安装

    Node.js安装 目录 Node.js简单介绍 windows安装Node.js Linux安装Node.js ...

  • node.js基础

    什么是node.js Node.js特点 node.js优点和缺点

  • Nodejs.2

    参考内容:Node.js EventEmitter 四、Node.js EventEmitter Node.js所...

  • nodejs第一步

    Node.js 是什么?Node.js与JavaScript的区别是什么? Node.js的优点?Node.js的...

  • node 学习笔记.md

    Node.js第一天 1. 初识Node.js 1.1 Node.js是什么 Node.js® is a Java...

  • Node.js学习

    主线:Node.js是什么 --> Node.js的组成 --> Node.js的特点 --> Helloworl...

  • 使用AngularJS搭建前台框架

    Node.js部署: 下载安装包:从Node.js官网下载Node.js安装包。 安装Node.js:打开node...

  • Node.js模块

    Node.js 模块和 Node.js 包介绍。 一、Node.js模块 每一个Node.js都是一个Node.j...

  • 小鹅通视频下载mac 小鹅通课程下载教程

    前两天,Node.js官方发布了Node.js 15的正式版本,Node.js 15 将替代 Node.js 14...

  • node学习笔记

    node.js 介绍 node.js初识 node.js 平台是基于 Chrome V8 JavaScript 引...

网友评论

    本文标题:Node.js

    本文链接:https://www.haomeiwen.com/subject/gamrcxtx.html