SlideShare a Scribd company logo
1 of 17
Trace Node.js
gd
Node.js - Architecture
v8 libuv
C++ binding modules
Js native modulesjavascript
C++
Outline
• libuv
• V8
• Node.js modules
libuv
• libuv enforces an asynchronous, event-driven style
of programming
Libuv – hollow world
• Callback
V8
• V8 provides C++ API
o Access Javascript object in C++
o Access C++ objects in Javascript
Terms
• Handler: An object reference managed by
the v8 garbage collector
• HandlerScopes: A stack-allocated class that
governs a number of local handles
• Context: A sandboxed execution context
with its own set of built-in objects and
functions
• Templaates: A template is a blueprint for
JavaScript functions and objects in a
context.
Samples
• Samples/shell.c
o Main()
o CreateShellContext()
Core modules
• C++ modules (src/node_extensions.cc)
o fs
o http_parser
o os
o Zlib
o …
• Js modules (lib/)
o fs.js
o http.js
o net.js
o os.js
o modules.js
o …
How to use core modules ?
…
var util = require('util');
var pathModule = require('path');
var binding = process.binding('fs');
var constants = process.binding('constants');
var fs = exports;
…
Lib/fs.js
How modules inited ?
node::Start(argc, argv)
// Use original argv, as we're just copying values out of it.
Handle<Object> process_l = SetupProcessObject(argc, argv);
v8_typed_array::AttachBindings(context->Global());
// Create all the objects, load modules, do everything.
// so your next reading stop should be node::Load()!
Load(process_l);
// All our arguments are loaded. We've evaluated all of the scripts. We
// might even have created TCP servers. Now we enter the main eventloop. If
// there are no watchers on the loop (except for the ones that were
// uv_unref'd) then this function exits. As long as there are active
// watchers, it blocks.
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
C++ modules
• What process.binding (a.k.a Node::Binding)
do
o Check binding_cache if module is in cache
already
o If not cached, call node_extensions::get_builtin_module to
bind the c++ module and call the module’s
register_func()
• How C++ modules implemented
o node_file.cc
Js modules
• When when requiring a js module in native modules,
NativeModule.require() in node.js is called
o If require(“native_module”), return NativeModule
o If cached return getCached().exports
o else return new
NativeModule(id).compile().exports
• NativeModule(id).compile() reads
source and compiles source into js
object in js heap
Why NativeModule.require()
• src/node.js is invoked by node::Load() in src/node.cc, and
responsible for loading lib/*.js and bootstrapping the nodejs
core.
NativeModule.wrap = function(script) {
return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
};
NativeModule.wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'n});'
];
NativeModule.prototype.compile = function() {
var source = NativeModule.getSource(this.id);
source = NativeModule.wrap(source);
var fn = runInThisContext(source, this.filename, true);
fn(this.exports, NativeModule.require, this, this.filename);
this.loaded = true;
};
How to use core modules(revisit)
• Loading C++ module
process.binding(“fs”) -> get_builtin_module(“fs”) ->
NODE_MODULE(node_fs, node::InitFs)
• Loading js module
Require(“path”) -> NativeModule.require(“path”) ->
process.binding("natives")["path"] ->
DefineJavaScript() -> natives[] -> node_natives.h
More !!
• How to write a C++ module
o http://nodejs.org/api/addons.html
• How about user-defined js module
o lib/modules.js
o http://nodejs.org/api/modules.html
Ref
• 深入浅出Node.js, http://vdisk.weibo.com/s/G-
kaugh6Z1f6
• Node.js源码研究之模块组织加载,
http://developer.51cto.com/art/201109/290287.htm
• http://nikhilm.github.io/uvbook/basics.html
• https://developers.google.com/v8/embed

More Related Content

What's hot

Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
Dinh Pham
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
Behrad Zari
 

What's hot (20)

Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Intro to node and non blocking io
Intro to node and non blocking ioIntro to node and non blocking io
Intro to node and non blocking io
 
Vert.x v3 - high performance polyglot application toolkit
Vert.x v3 - high performance  polyglot application toolkitVert.x v3 - high performance  polyglot application toolkit
Vert.x v3 - high performance polyglot application toolkit
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
 
Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming  Node.js and How JavaScript is Changing Server Programming
Node.js and How JavaScript is Changing Server Programming
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
node.js dao
node.js daonode.js dao
node.js dao
 
Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJS
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Node.js Enterprise Middleware
Node.js Enterprise MiddlewareNode.js Enterprise Middleware
Node.js Enterprise Middleware
 
NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an Introduction
 
NodeJS
NodeJSNodeJS
NodeJS
 
NodeJS
NodeJSNodeJS
NodeJS
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
 

Viewers also liked

I18n
I18nI18n
I18n
soon
 

Viewers also liked (20)

Where Node.JS Meets iOS
Where Node.JS Meets iOSWhere Node.JS Meets iOS
Where Node.JS Meets iOS
 
I18n
I18nI18n
I18n
 
Intro to appcelerator
Intro to appceleratorIntro to appcelerator
Intro to appcelerator
 
What grunt?
What grunt?What grunt?
What grunt?
 
Running Node Applications on iOS and Android
Running Node Applications on iOS and AndroidRunning Node Applications on iOS and Android
Running Node Applications on iOS and Android
 
Titanium appcelerator kickstart
Titanium appcelerator kickstartTitanium appcelerator kickstart
Titanium appcelerator kickstart
 
Python for AngularJS
Python for AngularJSPython for AngularJS
Python for AngularJS
 
Nodejs getting started
Nodejs getting startedNodejs getting started
Nodejs getting started
 
Implement Dependency Injection in Java
Implement Dependency Injection in JavaImplement Dependency Injection in Java
Implement Dependency Injection in Java
 
Groovy to gradle
Groovy to gradleGroovy to gradle
Groovy to gradle
 
Zookeeper
ZookeeperZookeeper
Zookeeper
 
Ultimate Guide to 30+ API Documentation Solutions
Ultimate Guide to 30+ API Documentation SolutionsUltimate Guide to 30+ API Documentation Solutions
Ultimate Guide to 30+ API Documentation Solutions
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
Getting Started with Angular 2
Getting Started with Angular 2Getting Started with Angular 2
Getting Started with Angular 2
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
The Enterprise Case for Node.js
The Enterprise Case for Node.jsThe Enterprise Case for Node.js
The Enterprise Case for Node.js
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 

Similar to Node.js code tracing

MattsonTutorialSC14.pptx
MattsonTutorialSC14.pptxMattsonTutorialSC14.pptx
MattsonTutorialSC14.pptx
gopikahari7
 

Similar to Node.js code tracing (20)

Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Swift after one week of coding
Swift after one week of codingSwift after one week of coding
Swift after one week of coding
 
uRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orguRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.org
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
 
Android OpenGL ES Game ImageGrabber Final Report
Android OpenGL ES Game ImageGrabber Final ReportAndroid OpenGL ES Game ImageGrabber Final Report
Android OpenGL ES Game ImageGrabber Final Report
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Nodejs overview
Nodejs overviewNodejs overview
Nodejs overview
 
Node.js/io.js Native C++ Addons
Node.js/io.js Native C++ AddonsNode.js/io.js Native C++ Addons
Node.js/io.js Native C++ Addons
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
Node Architecture.pptx
Node Architecture.pptxNode Architecture.pptx
Node Architecture.pptx
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
Node.js
Node.jsNode.js
Node.js
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
Liferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for DevelopersLiferay (DXP) 7 Tech Meetup for Developers
Liferay (DXP) 7 Tech Meetup for Developers
 
Node js internal
Node js internalNode js internal
Node js internal
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
MattsonTutorialSC14.pptx
MattsonTutorialSC14.pptxMattsonTutorialSC14.pptx
MattsonTutorialSC14.pptx
 

Recently uploaded

Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Recently uploaded (20)

Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 

Node.js code tracing

  • 2. Node.js - Architecture v8 libuv C++ binding modules Js native modulesjavascript C++
  • 4. libuv • libuv enforces an asynchronous, event-driven style of programming
  • 5. Libuv – hollow world • Callback
  • 6. V8 • V8 provides C++ API o Access Javascript object in C++ o Access C++ objects in Javascript
  • 7. Terms • Handler: An object reference managed by the v8 garbage collector • HandlerScopes: A stack-allocated class that governs a number of local handles • Context: A sandboxed execution context with its own set of built-in objects and functions • Templaates: A template is a blueprint for JavaScript functions and objects in a context.
  • 9. Core modules • C++ modules (src/node_extensions.cc) o fs o http_parser o os o Zlib o … • Js modules (lib/) o fs.js o http.js o net.js o os.js o modules.js o …
  • 10. How to use core modules ? … var util = require('util'); var pathModule = require('path'); var binding = process.binding('fs'); var constants = process.binding('constants'); var fs = exports; … Lib/fs.js
  • 11. How modules inited ? node::Start(argc, argv) // Use original argv, as we're just copying values out of it. Handle<Object> process_l = SetupProcessObject(argc, argv); v8_typed_array::AttachBindings(context->Global()); // Create all the objects, load modules, do everything. // so your next reading stop should be node::Load()! Load(process_l); // All our arguments are loaded. We've evaluated all of the scripts. We // might even have created TCP servers. Now we enter the main eventloop. If // there are no watchers on the loop (except for the ones that were // uv_unref'd) then this function exits. As long as there are active // watchers, it blocks. uv_run(uv_default_loop(), UV_RUN_DEFAULT);
  • 12. C++ modules • What process.binding (a.k.a Node::Binding) do o Check binding_cache if module is in cache already o If not cached, call node_extensions::get_builtin_module to bind the c++ module and call the module’s register_func() • How C++ modules implemented o node_file.cc
  • 13. Js modules • When when requiring a js module in native modules, NativeModule.require() in node.js is called o If require(“native_module”), return NativeModule o If cached return getCached().exports o else return new NativeModule(id).compile().exports • NativeModule(id).compile() reads source and compiles source into js object in js heap
  • 14. Why NativeModule.require() • src/node.js is invoked by node::Load() in src/node.cc, and responsible for loading lib/*.js and bootstrapping the nodejs core. NativeModule.wrap = function(script) { return NativeModule.wrapper[0] + script + NativeModule.wrapper[1]; }; NativeModule.wrapper = [ '(function (exports, require, module, __filename, __dirname) { ', 'n});' ]; NativeModule.prototype.compile = function() { var source = NativeModule.getSource(this.id); source = NativeModule.wrap(source); var fn = runInThisContext(source, this.filename, true); fn(this.exports, NativeModule.require, this, this.filename); this.loaded = true; };
  • 15. How to use core modules(revisit) • Loading C++ module process.binding(“fs”) -> get_builtin_module(“fs”) -> NODE_MODULE(node_fs, node::InitFs) • Loading js module Require(“path”) -> NativeModule.require(“path”) -> process.binding("natives")["path"] -> DefineJavaScript() -> natives[] -> node_natives.h
  • 16. More !! • How to write a C++ module o http://nodejs.org/api/addons.html • How about user-defined js module o lib/modules.js o http://nodejs.org/api/modules.html
  • 17. Ref • 深入浅出Node.js, http://vdisk.weibo.com/s/G- kaugh6Z1f6 • Node.js源码研究之模块组织加载, http://developer.51cto.com/art/201109/290287.htm • http://nikhilm.github.io/uvbook/basics.html • https://developers.google.com/v8/embed