Tự tạo module trong Node.js – Cách import, export module Node.js

Tự tạo module trong Node.js – Cách import, export module Node.js

(Xem lại: Module trong Node.js là gì – Cách dùng module Node.js)

Trong bài này mình sẽ hướng dẫn cách tạo một module trong Node.js và sử dụng module đó.

Tạo module trong Node.js

Bản chất module trong Node.js là một thư viện, nó có thể là 1 file .js, một hoặc 1 tập các file .js nhằm thực hiện 1 chức năng nào đấy.

Ở đây mình sẽ tạo module đơn giản là một .js chứa các biến, phương thức và class (variable, function, class) sau đó sử dụng lại các biến, phương thức và class này ở một file .js khác.

Ví dụ mình tạo file my-module.js gồm method hello(), biến PIclass Rectangle

// A function
hello = function() {
  console.log('hello world!')
}

// A variable
const PI = 3.14;

// A class!!
var Rectangle = class {

   constructor(length, width) {
     this.length = length;
     this.width = width;
   }
   showInfo() {
     console.log(`Rectangle ${this.width} x ${this.length} :`)
   }
   showArea()  {
     console.log("Area: " + (this.length * this.width))
   }
   showCircuit()  {
     console.log("Circuit: " + (2 * (this.length + this.width)))
   }
};

Tuy nhiên để sử dụng được các biến, function, class trong file my-module.js ta phải export nó ra tức là làm sao để cho các file javascript khác nhìn thấy các thông tin này.

(Mình giải thích chỗ này một chút: ở Java hay C# hay các ngôn ngữ hướng đối tượng khác mỗi file là 1 class ví dụ trong Java mỗi file .java là 1 class luôn, nên khi muốn sử dụng nó ở class khác ta chỉ cần khởi tạo với từ khóa new là có thể dùng được còn trong Javascript các thông tin trong 1 file như biến, funtion… lại có thể không liên quan gì đến nhau nên ta cần có 1 bước export)

Export thông tin trong module

Cách 1: chỉ export 1 thông tin nào đó:

ví dụ mình chỉ export method hello() thì ta sẽ thêm đoạn sau vào file my-module.js

module.exports = hello;

Khi đó tả chỉ có thể sử dụng method hello ở các file khác ví dụ:

var myModule = require("my-module")

myModule()

Ở đoạn code trên, nó sẽ hiểu myModule chính là method hello nên ta chỉ cần gọi myModule() tương đương với gọi method hello()

Kết quả:

hello world!

Cách 2: Export nhiều thông tin:

Trong cách này ta sẽ gộp các thông tin cần export thành 1 đối tượng và export đối tượng đó ra bên ngoài, khi muốn sử dụng thông tin nào thì ta sử dụng thông qua đối tượng được export.

Ví dụ: Đoạn code sau tương đương với việc export 1 đối tượng chứa method hello() và biến PI

module.exports.hello = hello;
module.exports.PI = PI;

Tương tự ta có thể export như sau:

var objectExport = {
  hello : hello,
  PI : PI,
  Rectangle : Rectangle,
}

module.exports = objectExport;

hoặc

module.exports = {
  hello : hello,
  PI : PI,
  Rectangle : Rectangle,
}

Khi sử dụng ta gọi nó thông qua đối tượng được export:

Ví dụ:

var myModule = require("my-module")

myModule.hello()

console.log('PI: ' + myModule.PI)

var rectangle = new myModule.Rectangle(2,3)
rectangle.showInfo()
rectangle.showArea()
rectangle.showCircuit()

Kết quả:

Tự tạo module trong Node.js - Cách import, export module Node.js

Cách 3: Sử dụng từ khóa import và export của ES6

Với cách này thì ta sẽ linh hoạt hơn trong việc sử dụng, ví dụ trong module ta export nhiều thứ trong khi sử dụng ta sẽ quyết định được những thông tin nào sẽ được import

Ví dụ:

import {PI,hello} from "my-module.js"
hello()
console.log("PI = " + PI)

Vị trí đặt module trong project Node.js

Vị trí đặt module trong project Node.js

Ở trên là project ví dụ của mình. Mặc định khi bạn dùng từ khóa require để lấy module nó sẽ tìm trong folder node_modules (đây là folder mặc định chứa các module, các module được cài đặt từ npm cũng sẽ nằm ở đây)

Do đó nêu muốn đặt module của bạn ở các vị trí khác thì bạn phải dùng đường dẫn tương đối trong method require

Ví dụ: với file my-module-1.js hoặc my-module-2.js ta phải khai báo như sau:

// with file my-module-2.js
var myModule = require("./my-module-2")

// with file my_modules/my-module-1.js
var myModule = require("./my_modules/my-module-1")

Tự tạo module trong Node.js – Cách import, export module Node.js stackjava.com

Okay, Done!

Download code ví dụ trên tại đây.

 

References:

https://www.w3schools.com/nodejs/nodejs_modules.asp

stackjava.com