博客
关于我
Node.js的模块
阅读量:229 次
发布时间:2019-03-01

本文共 1097 字,大约阅读时间需要 3 分钟。

在编写稍大一点的程序时,Node.js推荐将代码模块化处理。每个模块通常对应一个文件,文件路径即为模块名。

在编写每个模块时,开发者可以使用requireexportsmodule等预定义变量。

内置模块

Node.js自带众多内置模块,无需额外安装即可使用。例如:

  • assert – 用于断言检查
  • buffer – 用于处理二进制数据缓冲
  • child_process – 用于创建子进程
  • cluster – 用于处理多核CPU任务

模块的使用

可以通过require()方法加载模块:

var http = require('http');
示例

例如,使用HTTP模块创建服务器:

var http = require('http');  http.createServer(function (req, res) {      res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});      res.end('侠课岛');  }).listen(8888);

创建自定义模块

可以创建自己的模块,然后在应用程序中使用。

示例

创建一个返回日期和时间的模块(保存为mymodule.js):

exports.myDateTime = function () {      return Date();  };

然后在Node.js文件中使用该模块:

var http = require('http');  var dt = require('./mymodule');  http.createServer(function (req, res) {      res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});      res.write("当前日期和时间为:  " + dt.myDateTime());      res.end();  }).listen(8888);

注意:使用./表示模块与当前文件在同一目录下。

将代码保存到test_module.js并运行:

node test_module.js

运行后可在浏览器访问显示日期和时间。

乱码问题解决

如果出现中文乱码问题,需在响应头中添加字符编码:

res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});

charset=utf-8设置为UTF-8编码,支持所有Unicode字符。

转载地址:http://hfcv.baihongyu.com/

你可能感兴趣的文章
Orcale表被锁
查看>>
svn访问报错500
查看>>
sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
查看>>
ORCHARD 是什么?
查看>>
Struts2中使用Session的两种方法
查看>>
Stream API:filter、map和flatMap 的用法
查看>>
STM32工作笔记0032---编写跑马灯实验---寄存器版本
查看>>
ssm旅游信息管理系统的设计与实现bus56(程序+开题)
查看>>
order by rand()
查看>>
SSM(Spring+SpringMvc+Mybatis)整合开发笔记
查看>>
ViewHolder的改进写法
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
sql查询中 查询字段数据类型 int 与 String 出现问题
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>