class: center, middle # Node.js feature livecoding Anna Henningsen
she/her
@addaleax Slides @ https://addaleax.net/livecoding-nodeconfco19/
Node.js TSC
Active Node.js contributor since December 2015 --- # Node.js feature: setTimeout() #### Where does `setTimeout()` come from??? -- (Hint: It’s *not* the language!) --- # Node.js feature: setTimeout() - `setTimeout()`: Managed by event loop → libuv ```js const socket = net.connect(80, 'google.com', () => { console.log('connected'); }); setTimeout(() => { socket.end(); }, 1000); ``` What does the event loop do here? --- # Node.js feature: setTimeout() - `setTimeout()`: Managed by event loop → libuv - libuv central concepts: handles vs requests - `uv_handle_t`: Long-lasting, multi-event (e.g. net Socket) - `uv_req_t`: Oneshot (e.g. net connect, fs ops) - libuv provides timers as … -- **handles** --- # Data stored for a timer - Actual timeout function - libuv data (`uv_timer_t`) - includes event loop, timeout duration, native callback, etc. - C++ object - JS object - Async tracking --- # Node.js helper classes (All entirely internal, may change anytime) - `MemoryRetainer` – C++ objects that show up in heap dump - `BaseObject` – JS ↔ C++ binding connection - `AsyncWrap` – C++ objects that enter JS - `ReqWrap` – Associated with libuv requests - `HandleWrap` – Associated with libuv handles - … - … - … --- # `HandleWrap` comes builtin with … - Heap dump detection ability (`MemoryRetainer`) - A JS object (`BaseObject`) - Async tracking (`AsyncWrap`) - Methods for libuv handles (`.ref()`, `.unref()`, `.close()`) --- # What we want to write in C++ (in JS) ```js class TimerWrap extends HandleWrap { constructor(env, object /* actual JS object */) { super(env, object, this.timer, PROVIDER_TIMER); this.timer.init(env.event_loop()); } start(timeout_ms) { this.timer.start(TimerWrap.Callback, timeout_ms, 0); } static Callback(timer) { timer.object.ontimeout(); } } ``` --- # Node.js layers - Public modules: e.g. `timers` as `lib/timers.js` - Internal modules: `lib/internal/...` - C++ modules: `src/...`, accessed through `internalBinding()` --- # Thank you! Now for the exciting part :) - https://twitter.com/addaleax/ Slides @ https://addaleax.net/livecoding-nodeconfco19/