导出模块
导出模块
- module.exports或exports是一个特殊对象,默认情况下包含在Node.js应用程序的每个JS文件中。模块是表示当前模块的变量,导出是将作为模块公开的对象。因此,无论您分配给module.exports还是export,都将作为模块公开。
- 让我们看看如何使用module.exports将不同类型公开为模块
- 出口文字:
- 导出公开给您指定的模块有一个模块,因为它是一个对象。例如,如果您指定字符串文字,那么它会将该字符串文字公开为模块。
- 以下示例将一个简单的字符串消息公开为Message.js中的模块。
module.exports ='Hello Manasa';
//或exports ='Hello Manasa'; |
- 现在,导入此消息模块并使用它,如下所示。
App.js
var msg = require('。/ message.js'); 的console.log(MSG); |
- 您必须将“./”指定为根文件夹的路径才能导入本地模块。但是,您无需在require()函数中指定导入Node.js核心模块或NPM模块的路径。
- 运行App.js.
导出对象
- 导出是一个对象。因此,您可以附加属性或方法。以下示例在Message.js文件中公开具有字符串属性的对象
exports.SimpleMessage ='Hello kavya';
//或module.exports.SimpleMessage ='Hello kavya'; |
- 在上面的示例中,我们将一个属性“SimpleMessage”附加到exports对象。现在,导入并使用此模块,如下所示。
App.js:
var msg = require('./ Messages.js'); 的console.log(msg.SimpleMessage); |
- require()函数将返回一个对象{SimpleMessage:'Hello World'}并将其分配给msg变量。所以,现在你可以使用msg.SimpleMessage。
- 与上面相同,您可以使用函数公开对象。以下示例将具有日志功能的对象公开为模块。
Log.js:
module.exports.log = function(msg) {console.log(msg); }; |
- 上面的模块将公开一个对象 – {log:function(msg){console.log(msg); }。使用上面的模块,如下所示。
App.js
var msg = require('./ Log.js'); msg.log('Hello Mahendra'); |
- 运行文件:node app.js
- 可以将对象附加到模块.export,如下所示。
data.js
module.exports = {firstName:'Shahrukh', lastName:'汗'} |
- 现在创建app.js.
app.js
var person = require('./ data.js'); console.log(person.firstName +''+ person.lastName); |
- 运行app.js.
- 导出功能
- 您可以附加匿名函数以导出对象,如下所示。
Log.js
module.exports = function(msg){ 的console.log(MSG); }; |
- 现在您可以使用上面的模块,如下所示:
app.js
var msg = require('./ Log.js'); msg('hello Safiya'); |
- 运行app.js: – node app.js
导出函数作为一个类
- 函数可以像类一样对待。以下示例公开了可用作类的函数。
- 在JavaScript中,函数可以像类一样对待。以下示例公开了可用作类的函数。
Person.js
module.exports = function(firstName,lastName){ this.firstName = firstName; this.lastName = lastName; this.fullName = function(){ return this.firstName +''+ this.lastName; } } |
- Person.js可以如下所示使用: –
app.js
var person = require('./ Person.js'); var person1 = new person('Swaleha','Khan');的console.log(person1.fullName()); |
- 使用命令:-node app.js在Node.js命令提示符下运行app.js.