Saturday 22 December 2018

node.js: module.exports vs exports

In this post, I am going to explain the difference between module.exports and exports.

Whenever you load a module using require() function, it returns module.exports object of that module.

For example,
util.js
module.exports = {
	productName : "chat server",
	version : "1.2.3"	
}

index.js
util = require("./util.js")

console.log(`name : ${util.productName}`)
console.log(`version : ${util.version}`)

Execute the command ‘node index.js’, you can see below messages in console.

name : chat server
version : 1.2.3

What is exports?
exports is a reference to module.exports. If you attach any property to exports those are attached to module.exports also.


util.js
module.exports.productName = "chat server"

// Adding properties using exports
exports.version = "1.2.3"
exports.vendor = "ABC Corporation"

index.js
util = require("./util.js")

console.log(`name : ${util.productName}`)
console.log(`version : ${util.version}`)
console.log(`vendor : ${util.vendor}`)

Run index.js, you can see below messages in console.

name : chat server
version : 1.2.3
vendor : ABC Corporation

if module.exports pointing to some other object directly, then the properties exposed by export are ignored.


util.js
module.exports = {
	productName : "chat server"
}

// Adding properties using exports, these will be ignored
exports.version = "1.2.3"
exports.vendor = "ABC Corporation"

index.js
util = require("./util.js")

console.log(`name : ${util.productName}`)
console.log(`version : ${util.version}`)
console.log(`vendor : ${util.vendor}`)

Output
name : chat server
version : undefined
vendor : undefined


As you see the output, vendor and version details are undefined. It is because, module.exports is assigned to another object directly. So whatever you exposed via export will be ignored.


Previous                                                 Next                                                 Home

No comments:

Post a Comment