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
-
requireis a function in Node.js used to load modules. We useExpressandMongoosefor 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.
var notGlobal;
function func1() {}
function func2() {}
module.exports = {func1: func1, func2: func2};
Non-blocking
r1 = step1();
console.log('step1 done', r1);
r2 = step2(r1);
console.log('step2 done', r2);
r3 = step3(r2);
console.log('step3 done', r3);
console.log('All Done!');
If step() function doesn’t block, then it’s ok.
step1(function (r1) {
console.log('step1 done', r1);
step2(r1, function (r2) {
console.log('step2 done', r2);
step3(r2, function (r3) {
console.log('step3 done', r3);
console.log('All Done!'); // Correct
});
});
});
console.log('All Done!'); // Wrong!
If the function is blocking, use callbacks.
Listener and Emitter
myEmitter.on('myEvent', function(param1, param2) {
console.log('myEvent occurred with ' + param1 + ' and ' + param2 + '!');
});
myEmitter.emit('myEvent', 'arg1', 'arg2');
On emit call listeners are called synchronously and in the order the listeners were registered.
Have multiple different events for different state or actions:
myEmitter.on('conditionA', doConditionA);
myEmitter.on('conditionB', doConditionB);
myEmitter.on('conditionC', doConditionC);
myEmitter.on('error', handleErrorCondition);
Stanford CS142 笔记 - Node.js
http://example.com/2024/10/30/CS142/nodejs/