Linh Ngo
Nodejs developer. Working in a tech education company - Techmastervn with a vision to promote STEM and provide valuable as well as affordable IT training to students and young adults
Sơ đồ Nodejs theo cấp low-level -> high-level
Sơ đồ Nodejs theo quy trình hoạt động
Libuv chính là thư viện quản lý và xử lý các yêu cầu bất đồng bộ trong Node
Xử lý tác vụ bất đồng bộ
Ví dụ với HTTP requests
Nodejs Server
// main.js
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");// chạy file trên terminal
$ node main.jsBlocking request
Non-Blocking request
// main.js
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");// Output
Welcome to Techmaster's Nodejs Course !!!!
Program Ended// Output
Program Ended
Welcome to Techmaster's Nodejs Course !!!!
Nguồn dữ liệu
Điểm đến
Buffer - nơi lưu dữ liệu tạm thời
NODE SERVER
Writable HTTP Response
Readable HTTP Request
CLIENTS
Góc nhìn của Node Server
Stream là collections của data, giống như là mảng hay string.Sự khác biệt là stream tất cả mọi thứ không cùng tồn tại ở một thời điểm, và nó không phù hợp để lưu tất cả trong bộ nhớ
// Mỗi 1 file code đều được Nodejs
// tự động thêm các dòng code sau
var module = { exports: {} };
var exports = module.exports;
// code thực tế của bạn ở đây
return module.exports;module.exports vs exports
// abc.js
var name = "Techmaster";
var getName = function(){
return name
}
exports = name;
module.exports.getName = getName; // Output khi require
const A = require('./abc.js')
console.log(A); // trả về cái gì ???
exports không còn trỏ đến object lúc đầu tại vùng nhớ A nữa, mà chỉ đến 1 vùng nhớ X khác
không xuất dữ liệu bằng keyword exports theo kiểu gán dữ liệu thẳng cho biến exports được
// abc.js
var name = "Techmaster";
var getName = function(){
return name
}
exports.name = name;
module.exports.getName = getName;Phải gán dữ liệu vào 1 thuộc tính của exports
Note: tìm hiểu thêm về cách JS pass by value (tham trị) hay pass by reference (tham chiếu)
By Linh Ngo