SlideShare a Scribd company logo
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 (20)

PDF
Node Architecture and Getting Started with Express
jguerrero999
 
PPTX
Introduction Node.js
Erik van Appeldoorn
 
PPTX
NodeJS - Server Side JS
Ganesh Kondal
 
PPTX
Intro to node and non blocking io
Amy Hua
 
PPTX
Vert.x v3 - high performance polyglot application toolkit
Sages
 
PDF
Introduction to Node.js
Rob O'Doherty
 
ODP
Asynchronous I/O in NodeJS - new standard or challenges?
Dinh Pham
 
PDF
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
KEY
Introduction to node.js
jacekbecela
 
KEY
node.js dao
Vladimir Miguro
 
PDF
Philly Tech Week Introduction to NodeJS
Ross Kukulinski
 
PDF
Server Side Event Driven Programming
Kamal Hussain
 
PDF
How to Test Asynchronous Code (v2)
Felix Geisendörfer
 
PPTX
introduction to node.js
orkaplan
 
PDF
Node.js Enterprise Middleware
Behrad Zari
 
PDF
NodeJS: an Introduction
Roberto Casadei
 
KEY
NodeJS
.toster
 
PDF
NodeJS
LinkMe Srl
 
PPTX
Intro to Node.js (v1)
Chris Cowan
 
PDF
NodeJS ecosystem
Yukti Kaura
 
Node Architecture and Getting Started with Express
jguerrero999
 
Introduction Node.js
Erik van Appeldoorn
 
NodeJS - Server Side JS
Ganesh Kondal
 
Intro to node and non blocking io
Amy Hua
 
Vert.x v3 - high performance polyglot application toolkit
Sages
 
Introduction to Node.js
Rob O'Doherty
 
Asynchronous I/O in NodeJS - new standard or challenges?
Dinh Pham
 
Node.js and How JavaScript is Changing Server Programming
Tom Croucher
 
Introduction to node.js
jacekbecela
 
node.js dao
Vladimir Miguro
 
Philly Tech Week Introduction to NodeJS
Ross Kukulinski
 
Server Side Event Driven Programming
Kamal Hussain
 
How to Test Asynchronous Code (v2)
Felix Geisendörfer
 
introduction to node.js
orkaplan
 
Node.js Enterprise Middleware
Behrad Zari
 
NodeJS: an Introduction
Roberto Casadei
 
NodeJS
.toster
 
NodeJS
LinkMe Srl
 
Intro to Node.js (v1)
Chris Cowan
 
NodeJS ecosystem
Yukti Kaura
 

Viewers also liked (20)

PDF
Where Node.JS Meets iOS
Sam Rijs
 
KEY
I18n
soon
 
PDF
Intro to appcelerator
Dave Hudson
 
ODP
What grunt?
Lucio Martinez
 
PPTX
Running Node Applications on iOS and Android
ukadakal
 
KEY
Titanium appcelerator kickstart
Alessio Ricco
 
PDF
Python for AngularJS
Jeff Schenck
 
PPTX
Nodejs getting started
Triet Ho
 
PPTX
Implement Dependency Injection in Java
Geng-Dian Huang
 
PPTX
Groovy to gradle
Geng-Dian Huang
 
PDF
Zookeeper
Geng-Dian Huang
 
PDF
Ultimate Guide to 30+ API Documentation Solutions
Bill Doerrfeld
 
PDF
Introduction to Nodejs
Gabriele Lana
 
PPTX
Nodejs intro
Ndjido Ardo BAR
 
PDF
Getting Started with Angular 2
FITC
 
PDF
Nodejs Explained with Examples
Gabriele Lana
 
PPTX
Introduction to Node.js
Vikash Singh
 
PDF
Node Foundation Membership Overview 20160907
NodejsFoundation
 
PDF
The Enterprise Case for Node.js
NodejsFoundation
 
PDF
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
Where Node.JS Meets iOS
Sam Rijs
 
I18n
soon
 
Intro to appcelerator
Dave Hudson
 
What grunt?
Lucio Martinez
 
Running Node Applications on iOS and Android
ukadakal
 
Titanium appcelerator kickstart
Alessio Ricco
 
Python for AngularJS
Jeff Schenck
 
Nodejs getting started
Triet Ho
 
Implement Dependency Injection in Java
Geng-Dian Huang
 
Groovy to gradle
Geng-Dian Huang
 
Zookeeper
Geng-Dian Huang
 
Ultimate Guide to 30+ API Documentation Solutions
Bill Doerrfeld
 
Introduction to Nodejs
Gabriele Lana
 
Nodejs intro
Ndjido Ardo BAR
 
Getting Started with Angular 2
FITC
 
Nodejs Explained with Examples
Gabriele Lana
 
Introduction to Node.js
Vikash Singh
 
Node Foundation Membership Overview 20160907
NodejsFoundation
 
The Enterprise Case for Node.js
NodejsFoundation
 
How to Make Awesome SlideShares: Tips & Tricks
SlideShare
 
Ad

Similar to Node.js code tracing (20)

PDF
Raffaele Rialdi
CodeFest
 
PDF
Swift after one week of coding
SwiftWro
 
PPTX
uRequire@greecejs: An introduction to http://uRequire.org
Agelos Pikoulas
 
PDF
Node.js extensions in C++
Kenneth Geisshirt
 
PPTX
JS & NodeJS - An Introduction
Nirvanic Labs
 
PPTX
Android OpenGL ES Game ImageGrabber Final Report
Jungsoo Nam
 
PDF
Using the Android Native Development Kit (NDK)
DroidConTLV
 
PDF
Advanced Node.JS Meetup
LINAGORA
 
PPTX
Nodejs overview
Nicola Del Gobbo
 
PPTX
Node.js/io.js Native C++ Addons
Chris Barber
 
PPTX
node.js.pptx
rani marri
 
PPTX
Node Architecture.pptx
Ahmed Hassan
 
PDF
Introduction to the Android NDK
BeMyApp
 
PDF
Tips and tricks for building high performance android apps using native code
Kenneth Geisshirt
 
PPTX
Liferay (DXP) 7 Tech Meetup for Developers
Azilen Technologies Pvt. Ltd.
 
PDF
Node js internal
Chinh Ngo Nguyen
 
PDF
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
JiandSon
 
PDF
Java Future S Ritter
catherinewall
 
PPTX
MattsonTutorialSC14.pptx
gopikahari7
 
Raffaele Rialdi
CodeFest
 
Swift after one week of coding
SwiftWro
 
uRequire@greecejs: An introduction to http://uRequire.org
Agelos Pikoulas
 
Node.js extensions in C++
Kenneth Geisshirt
 
JS & NodeJS - An Introduction
Nirvanic Labs
 
Android OpenGL ES Game ImageGrabber Final Report
Jungsoo Nam
 
Using the Android Native Development Kit (NDK)
DroidConTLV
 
Advanced Node.JS Meetup
LINAGORA
 
Nodejs overview
Nicola Del Gobbo
 
Node.js/io.js Native C++ Addons
Chris Barber
 
node.js.pptx
rani marri
 
Node Architecture.pptx
Ahmed Hassan
 
Introduction to the Android NDK
BeMyApp
 
Tips and tricks for building high performance android apps using native code
Kenneth Geisshirt
 
Liferay (DXP) 7 Tech Meetup for Developers
Azilen Technologies Pvt. Ltd.
 
Node js internal
Chinh Ngo Nguyen
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
JiandSon
 
Java Future S Ritter
catherinewall
 
MattsonTutorialSC14.pptx
gopikahari7
 
Ad

Recently uploaded (20)

PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PDF
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Server Side Web Development Unit 1 of Nodejs.pptx
sneha852132
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Thermal runway and thermal stability.pptx
godow93766
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 

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