Stanford CS142 笔记 - Node.js
Introduction
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser.
- Single-Threaded Event Loop: Node.js uses a single-threaded event loop. The Event Loop continuously checks the event queue to see if there are any events to be handled.
- Non-blocking I/O: Node.js performs I/O operations (like reading from a database or reading from a file) asynchronously. Instead of waiting for the operation to complete, Node.js registers a callback and moves on to handle the next event. This non-blocking behavior ensures that Node.js can handle many I/O operations concurrently without getting bogged down by slow operations
Module System
require
is a function in Node.js used to load modules. We useExpress
andMongoose
for web development.- System modules: Built-in Node.js modules like fs, http, path, etc.
- File modules: Like
require("./myModule.js")
- Directory modules: Like
require("./myModule")
, look formyModule/index.js
- In Node.js, every module (or file) has its own scope, module.exports allows us to make functions or variables available to other files.
1
2
3
4var notGlobal;
function func1() {}
function func2() {}
module.exports = {func1: func1, func2: func2};
Non-blocking
1 |
|
If step()
function doesn’t block, then it’s ok.
1 |
|
If the function is blocking, use callbacks.
Listener and Emitter
1 |
|
On emit call listeners are called synchronously and in the order the listeners were registered.
Have multiple different events for different state or actions:
1 |
|
Stanford CS142 笔记 - Node.js
https://thiefcat.github.io/2024/10/30/CS142/Nodejs/