“exports” và “module.exports” - quan1997ap/angular-app-note GitHub Wiki
Node.js coi mỗi một file javascript là một module nhỏ , độc lập với các file khác. Người ta gọi là tính đóng gói. Để một hàm trong file javascript có thể được sử dụng bởi file thì bạn cần phải export nó ra.
Giả sử trong package của bạn có 2 file javascript: one.js và two.js
Để two.js có thể gọi một hàm verifyPassword(...) trong one.js thì nó phải được export.
// one.js
exports.verifyPassword = function(user, password, done) { ... }
Khi bạn làm điều này, bất kể file nào require('one.js') đều có thể sử dụng hàm verifyPassword(...).
// two.js
require('one.js') // { verifyPassword: function(user, password, done) { ... } }
Tuy nhiên, làm thế nào để export trực tiếp hàm verifyPassword() mà không phải định nghĩa nó như một thuộc tính của one.js? Câu trả lời là sử dụng module.export
// one.js
module.exports = function(user, password, done) { ... }
Nhìn có vẻ đơn giản vậy thôi nhưng sự khác nhau giữa exports và module.exports đang trở thành chủ đề bàn tán của rất nhiều Node.js developer.