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 use Express and Mongoose 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 for myModule/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
    4
    var notGlobal;
    function func1() {}
    function func2() {}
    module.exports = {func1: func1, func2: func2};

Non-blocking

1
2
3
4
5
6
7
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.

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
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:

1
2
3
4
myEmitter.on('conditionA', doConditionA);
myEmitter.on('conditionB', doConditionB);
myEmitter.on('conditionC', doConditionC);
myEmitter.on('error', handleErrorCondition);

Stanford CS142 笔记 - Node.js
https://thiefcat.github.io/2024/10/30/CS142/Nodejs/
Author
小贼猫
Posted on
October 30, 2024
Licensed under