Node.js 模块


Node.js 中的模块是什么?

将模块视为与 JavaScript 库相同。

您想要包含在应用程序中的一组函数。


内置模块

Node.js 有一组内置模块,无需进一步安装即可使用。

看看我们的内置模块参考获取完整的模块列表。


包含模块

要包含模块,请使用require()带有模块名称的函数:

var http = require('http');

现在您的应用程序可以访问 HTTP 模块,并且能够创建服务器:

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Hello World!');
}).listen(8080);

创建您自己的模块

您可以创建自己的模块,并轻松地将它们包含在您的应用程序中。

以下示例创建一个返回日期和时间对象的模块:

示例

创建一个返回当前日期和时间的模块:

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

使用exports关键字使属性和方法在模块文件外部可用。

将上面的代码保存在名为 "myfirstmodule.js" 的文件中



包含您自己的模块

现在,您可以在任何 Node.js 文件中包含并使用该模块。

示例

在 Node.js 文件中使用模块 "myfirstmodule":

var http = require('http');
var dt = require('./myfirstmodule');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("The date and time are currently: " + dt.myDateTime());
  res.end();
}).listen(8080);
运行示例 »

请注意,我们使用./找到该模块,这意味着该模块与 Node.js 文件位于同一文件夹中。

将上面的代码保存在名为 "demo_module.js" 的文件中,并启动该文件:

启动demo_module.js:

C:\Users\ Your Name>node demo_module.js

如果您在计算机上执行了相同的步骤,您将看到与示例相同的结果:http://本地主机:8080