- vừa được xem lúc

[Node.js] Inner workings of Node.js

0 0 7

Người đăng: Vivian

Theo Viblo Asia

I. V8 Engine

  • V8 engine is JavaScript engine embedded in Node.js, it takes JS (computers cannot understand JavaScript) code and converts it into machine code.

II. Common used global objects

  • __dirname: returns the current directory's name you are in.
  • __filename: returns the absolute path to the current file you are in.
  • setTimeout
  • setInterval

III. Function expressions

  • Using function keyword to define a function inside an expression.
let greeting = function(){ console.log("Hello world!");
}
greeting();

IV. Module & require

1. module

  • Node.js treats all JS files as a separate module.
  • The code in each module is private to the module unless it is explicitly exported.
// greeting.js aka greeting module
let greeting = function(){ console.log("Hello world!");
}
let greeting2 = function(name){ console.log(`Welcome ${name} to Node.js!`);
}
module.exports = greeting; (1)
// or multiple exports
module.exports.greeting = greeting; (2) module.exports.greeting2 = greeting2;

2. require('something')

  • require keyword refers to a function used to import all objects exported from module.exports from other modules.
  • Values return by require function are equal to the module.exports
// app.js
let greeting = require("path-to-greet-module/greeting"); (1)
greeting(); // Hello world! let greetings = require("path-to-greet-module/greeting"); (2)
greetings.greeting(); // Hello world!
greetings.greeting2("Vivian"); // Welcome Vivian to Node.js!

V. Events module and event emitter

  • events module is used to create and handle custom events, it includes EventEmitter class.
  • EventEmitter is used to raise and handle custom events.
// gets ref of EventEmitter class
let events = require('events'); // creates an object of EventEmitter
let myEventEmitter = new events.EventEmitter(); // subscribes for slide using .on or .addListener
// callback fnc will be called when an event is raised
myEventEmitter.on("slide", (data) => { console.log("Slide is fired: " + data);
}); // raises slide event
myEventEmitter.emit("slide", "Slide smt");

VI. File system

  • fs module is used to create, read, update, delete and rename files asynchronously or synchronously.

1. Reading file

  • Synchronous operation with fs.readFileSync(path, options).
  • Options optional is an object containing the encoding for data specification and flag for operations allowed in the file. Default values are null and r respectedly.
  • This version will block code before its finished.
let fs = require('fs');
let output = fs.readFileSync('filename',{encoding: 'utf8', flag: 'r'}); // or 
let output = fs.readFileSync('filename','utf8'); // file's content
  • Asynchronous operation with fs.readFile(path, options,callbackFnc)
  • This version will NOT block code while its reading. callbackFnc is called after reading operation is done.
let fs = require('fs');
fs.readFile('filename','utf8',(err, data) => { if(err) console.log(err); else console.log(data); // file's content
});

2. Writing file

  • Synchronous operation with fs.writeFileSync(path,data, options).
  • Data can be a string, buffer TypedArray or DataView which can be written to file.
  • Options optional is an object containing the encoding for data specification, mode - an integer for file mode and flag for operations allowed in the file. Default values are utf8, 0o666 and w respectedly.
  • This version will block code before its finished.
  • NOTE: file will be created automatically if it does not exist.
let fs = require('fs');
let data = "Hello world";
fs.writeFileSync('filename',data); 
  • Asynchronous operation with fs.writeFile(path, data, options)
  • This version will NOT block code while its reading.
let fs = require('fs');
let data = "Hello world";
fs.writeFile('filename', data);

3. Creating & removing file/directory

  • Removing file
// Synchronous methods
fs.unlinkSync(path) // Asynchronous methods: delete file if it exists else throw error
fs.unlink(path, (err)=>{});
  • Creating & removing directory
 // Synchronous methods
fs.mkdirSync("path", options); fs.rmdirSync("path"); // Asynchronous methods
fs.mkdir("path", () => {});
fs.rmdir("path", () => {}); // throws error if directory is not empty

Bình luận

Bài viết tương tự

- vừa được xem lúc

Tìm hiểu sâu về những ngôn ngữ lập trình phổ biến trong phát triển Fullstack: Java, JavaScript (Node.js), Python và Ruby

Chào mừng bạn đến với blog của mình! Hôm nay, hãy cùng mình khám phá thế giới của ngôn ngữ lập trình Fullstack - một trạm dừng quan trọng cho bất kỳ ai muốn trở thành một lập trình viên Fullstack tài

0 0 14

- vừa được xem lúc

[Node.js] Creating Webserver (p1)

I. Client and server. . .

0 0 9

- vừa được xem lúc

[Node.js] Creating Webserver (p2)

I. Partial views. . .

0 0 6

- vừa được xem lúc

[CI-CD] Triển Khai Ứng Dụng Node.js lên Cloud Run với GitHub Actions

Cloud Run của Google Cloud Platform (GCP) cung cấp một nền tảng serverless để chạy các container được quản lý tự động. Kết hợp với GitHub Actions, bạn có thể tự động hóa quy trình triển khai (CI/CD) c

0 0 3

- vừa được xem lúc

[CI-CD] Triển khai CICD đơn giản cho Raspberry Pi

Trên công ty có ông bạn mang con Raspberry Pi B+ lên công ty dựng server để giám sát mạng, thế là mình xin ké 1 chân vào để deploy gì đấy vui vui . Thế là bắt đầu tìm ý tưởng lặt vặt dựng con server n

0 0 8