Module trong Node.js là gì – Tải, sử dụng module Nodejs

Module trong Node.js là gì – Tải, sử dụng module Nodejs

(Xem thêm: Các module trong Node.js)

(Xem thêm: Tạo mới module trong Node.js)

Module trong Node.js là gì?

Trong Node.js một module có thể hiểu là một thư viện, nó chứa một tập các hàm, đối tương, biến để phục vụ một chức năng nào đó.
Sử dụng module sẽ làm cho code của bạn nhìn ngắn gọn, đơn giản. Bạn chỉ cần include module vào là có thể sử dụng luôn các chức năng của module đó.

Cách sử dụng module trong Node.js

Để sử dụng module ta khai báo lệnh require(moduleName)

Ví dụ muốn include module http ta dùng lệnh (module http có sẵn trong Node.js nên không cần tải về nữa)

var http = require('http');
 Các biến, function của module http sẽ được thực thi thông qua biến var http

Ví dụ sử dụng module http để tạo http server

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

Cách tải và cài đặt module trong Node.js

Ngoài những module có sẵn sau khi cài Node.js ta có thể ta sử dụng các module khác từ repository.

Để tải một module nào đó ta sử dụng lệnh npm install module_name

Ví dụ muốn tải module nodemailer  (module nodemailer dùng để gửi email) ta dùng lệnh:

npm install nodemailer

Sau khi chạy nó sẽ tự động tải module nodemailer vào trong folder node_modules của project Node.js

Module trong Node.js là gì - Tải, sử dụng module Nodejs Module trong Node.js là gì - Tải, sử dụng module Nodejs

Hoăc bạn có thể khai báo module cần dùng trong file package.json sau đó dùng lệnh npm install để tải/cài đặt chúng

(Xem lại: quản lý module bằng npm)

 

Okay, Done!

Bài tiếp theo mình sẽ hướng dẫn cách tự tạo một module riêng và cách sử dụng, import , export các thành phần trong module đó.

 

References:
https://nodejs.org/api/

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

stackjava.com