SlideShare a Scribd company logo
1 of 21
Download to read offline
Extending Node.js
Using C++
Kenneth Geisshirt
Open Source Days 2013
About me
● Education
– B.Sc. in computer science (Univ. of Copenhagen)
– M.Sc. in chemistry (Univ. of Copenhagen)
– Ph.D. in soft material science (Roskilde Univ.)
● Freelance writer and tech review
● Senior software developer at TightDB, Inc.
– Documentation and benchmarking
– Implementing language bindings
Agenda
● What is Node.js and V8?
● C++ classes
● Wrapping classes
– Setters, getters, deleters, enumerators
– Anonymous functions
– Exceptions
– Instantiate objects
● Building extensions
Codeexamples
What is Node.js?
● Server-side JavaScript
● Based on Google V8
● Event-driven, non-blocking I/O
● Many modules
– Network, files, databases, etc.
– Mostly written in JavaScript
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = require('url').parse(req.url, true);
res.end('<html><body>Hello '+q.query.name+'</body></html>');
}).listen(9876, "127.0.0.1");
Google V8
● High performance JavaScript
engine
– Written in C++
– Incremental garbage collector
– Just-in-Time compilation (ARM, IA-32,
x86_64, MIPS)
– Used in Chrome and Chromium
● Classes for JavaScript types Object
Array Boolean FunctionStringDateNumber
C++ classes
● Person
– firstname
– lastname
– birthday
– to_str
● Book
– add
– lookup
– operator []
– remove
– size
Files:
book.hpp, book.cpp
person.hpp, person.cpp
main.cpp
Makefile
Wrapper classes
● Inherit from ObjectWrap
● Declaring friendships can be an advantage
● Common (static) methods:
– Method Init adds class to runtime
– Method New instantiates an object
● Remember that JavaScript has “funny” scope
rules
● Special exception class
● Validate arguments as JavaScript isn't strongly
typed
Wrapper classes
● Inherit from ObjectWrap
● Declaring friendships can be an advantage
● Common (static) methods:
– Method Init adds class to runtime
– Method New instantiates an object
● Remember that JavaScript has “funny” scope
rules
● Special exception class
● Validate arguments as JavaScript isn't strongly
typed
Initialize
● Method Init
– Sets the class name
– Sets the number of internal fields
– Adds methods to runtime
● NODE_SET_PROTOTYPE_METHOD macro
– Adds getter/setter/deleter/enumerator
– Create a constructor (function object)
Example: PersonWrap::Init and BookWrap::Init
Arguments
● Class Arguments are in methods
– An array of V8 objects
● Variable number of arguments
– Length method is useful
● Typical a lot of input validation
– IsString, IsArray, IsNumber, etc.
● The This() method returns the current object
– You must unwrap it to get your object
Example: BookWeap::Lookup
Scope
● Methods need access to the JavaScript stack
● A HandleScope object can help you
– Methods begin by creating the object
– Stack allocation (local variable)
● Exit methods by closing scope
– Returns a variable to the previous scope
– Scope cannot be used
– Garbage collector will eventually deallocate it
● Local<T> is for local (stack allocated) variables
Photo by Hertje Brodersen
Example: BookWrap::Length
(V8) Exceptions
● In JavaScript, you can throw any object
● V8 implements it as a C++ class
● Five different:
– RangeError, ReferenceError, SyntaxError,
TypeError, Error
● You throw by returning an exception object
– And it can be caught in you JavaScript program
Example: BookWrap::Add
New instance
● JavaScript programs can create new objects
– Or instances of you class
● The New method is called when a new object
is created
– Create a wrapper object
– Probably you must create a wrapped object, too
– Wrap this and return it
● The constructor can easily take arguments
Example: BookWrap::New
New instance from C++
● You can create JavaScript objects from C++
– Useful when a method returns a wrapped object
● Overload the New method
– Or use another name
● The constructor (of the wrapper class) has a
NewInstance method
● Pointer to wrapped object is added as internal
field
● Friendship between wrapper classes is very useful
Example: PersonWrap::New ×3
Getter and setter
● JavaScript has to index operators
– [] for array-like access (indexed)
– . for attributes (named)
● No negative index (uint32_t)
Examples: BookWrap::Getter and PersonWrap::Setter
Deleter and Enumerator
● JavaScript's delete operator is supported by
implementing a Deleter
– Must return either true or false
● An enumerator makes it possible to do
for ... in
Example: BookWrap::Deleter and BookWrap::Enumerator
Anonymous functions
● JavaScript programmers love anonymous
functions
– Functions are just an object → can be an
argument
● You must set the context
– JavaScript is complex
– Current one is often fine
● Set up the arguments
Example: BookWrap::Each
Catching Exceptions
● JavaScript functions can throw exceptions
– And you can catch them in C++
– The TryCatch class implement a handler
● Complication:
– JavaScript might return an object if successful
– But an exception is also an object
– (the V8 tutorial is probably wrong)
● You can rethrow exceptions
Example: BookWrap::Apply
Build
● Initialize classes from init
– File: funstuff_node.cpp
● Using old-school node-waf
– Write a wscript file
● Newer extensions use gyp
Where to go?
● Get my demo extension:
https://github.com/kneth/FunStuff
● Node.js: http://nodejs.org/
● JavaScript Unit Testing by Hazam Salah
● V8 classes:
http://bespin.cz/~ondras/html/hierarchy.html
Observations
● Extensions do not have to be a one-to-one
mapping
● A lot of code to do input validation
– JavaScript is not strongly typed!
● C++ has classes – JavaScript doesn't
– Awkward for JavaScript programmers
● Node.js extension can (relative) easily be
ported to Chrome
● Nodeunit is nice for unit testing

More Related Content

What's hot

Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSRoss Kukulinski
 
Swift after one week of coding
Swift after one week of codingSwift after one week of coding
Swift after one week of codingSwiftWro
 
Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript EngineGary Yeh
 
ooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wengerooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos WengerAmos Wenger
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js ModuleFred Chien
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Robert Schadek
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Kenneth Geisshirt
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 

What's hot (20)

Philly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJSPhilly Tech Week Introduction to NodeJS
Philly Tech Week Introduction to NodeJS
 
NodeJS
NodeJSNodeJS
NodeJS
 
Swift after one week of coding
Swift after one week of codingSwift after one week of coding
Swift after one week of coding
 
Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript Engine
 
NodeJS
NodeJSNodeJS
NodeJS
 
ooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wengerooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wenger
 
Turbo charging v8 engine
Turbo charging v8 engineTurbo charging v8 engine
Turbo charging v8 engine
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an Introduction
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
packet destruction in NS2
packet destruction in NS2packet destruction in NS2
packet destruction in NS2
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
NS2 Shadow Object Construction
NS2 Shadow Object ConstructionNS2 Shadow Object Construction
NS2 Shadow Object Construction
 
Basic Packet Forwarding in NS2
Basic Packet Forwarding in NS2Basic Packet Forwarding in NS2
Basic Packet Forwarding in NS2
 
NS2 Classifiers
NS2 ClassifiersNS2 Classifiers
NS2 Classifiers
 
Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...Asynchronous single page applications without a line of HTML or Javascript, o...
Asynchronous single page applications without a line of HTML or Javascript, o...
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
NS2 Object Construction
NS2 Object ConstructionNS2 Object Construction
NS2 Object Construction
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 

Similar to Extending Node.js using C++

Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Beyond Wordcount with spark datasets (and scalaing) - Nide PDX Jan 2018
Beyond Wordcount  with spark datasets (and scalaing) - Nide PDX Jan 2018Beyond Wordcount  with spark datasets (and scalaing) - Nide PDX Jan 2018
Beyond Wordcount with spark datasets (and scalaing) - Nide PDX Jan 2018Holden Karau
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Kai Chan
 
Building parsers in JavaScript
Building parsers in JavaScriptBuilding parsers in JavaScript
Building parsers in JavaScriptKenneth Geisshirt
 
Ch 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScriptCh 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScriptdcomfort6819
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageAsankhaya Sharma
 
Wattpad - Spark Stories
Wattpad - Spark StoriesWattpad - Spark Stories
Wattpad - Spark StoriesRylan Halteman
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Big data week presentation
Big data week presentationBig data week presentation
Big data week presentationJoseph Adler
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07Terry Yoast
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetHDR1001
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
JavaScript Getting Started
JavaScript Getting StartedJavaScript Getting Started
JavaScript Getting StartedHazem Hagrass
 
SDEC2011 Mahout - the what, the how and the why
SDEC2011 Mahout - the what, the how and the whySDEC2011 Mahout - the what, the how and the why
SDEC2011 Mahout - the what, the how and the whyKorea Sdec
 

Similar to Extending Node.js using C++ (20)

Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
Beyond Wordcount with spark datasets (and scalaing) - Nide PDX Jan 2018
Beyond Wordcount  with spark datasets (and scalaing) - Nide PDX Jan 2018Beyond Wordcount  with spark datasets (and scalaing) - Nide PDX Jan 2018
Beyond Wordcount with spark datasets (and scalaing) - Nide PDX Jan 2018
 
Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)Java Performance Tips (So Code Camp San Diego 2014)
Java Performance Tips (So Code Camp San Diego 2014)
 
Building parsers in JavaScript
Building parsers in JavaScriptBuilding parsers in JavaScript
Building parsers in JavaScript
 
Ch 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScriptCh 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScript
 
Design and Implementation of the Security Graph Language
Design and Implementation of the Security Graph LanguageDesign and Implementation of the Security Graph Language
Design and Implementation of the Security Graph Language
 
Wattpad - Spark Stories
Wattpad - Spark StoriesWattpad - Spark Stories
Wattpad - Spark Stories
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Big data week presentation
Big data week presentationBig data week presentation
Big data week presentation
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
01 objective-c session 1
01  objective-c session 101  objective-c session 1
01 objective-c session 1
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
JavaScript Getting Started
JavaScript Getting StartedJavaScript Getting Started
JavaScript Getting Started
 
SDEC2011 Mahout - the what, the how and the why
SDEC2011 Mahout - the what, the how and the whySDEC2011 Mahout - the what, the how and the why
SDEC2011 Mahout - the what, the how and the why
 

More from Kenneth Geisshirt

Building mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeBuilding mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeKenneth Geisshirt
 
Tales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleTales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleKenneth Geisshirt
 
Is the database a solved problem?
Is the database a solved problem?Is the database a solved problem?
Is the database a solved problem?Kenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Kenneth Geisshirt
 
Hadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxHadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxKenneth Geisshirt
 
JavaScript/Emacs integration
JavaScript/Emacs integrationJavaScript/Emacs integration
JavaScript/Emacs integrationKenneth Geisshirt
 
Introduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software DevelopmentIntroduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software DevelopmentKenneth Geisshirt
 

More from Kenneth Geisshirt (14)

Open Source in Real Life
Open Source in Real LifeOpen Source in Real Life
Open Source in Real Life
 
Building mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeBuilding mobile apps with Realm for React Native
Building mobile apps with Realm for React Native
 
micro:bit and JavaScript
micro:bit and JavaScriptmicro:bit and JavaScript
micro:bit and JavaScript
 
Tales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleTales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scale
 
Android things
Android thingsAndroid things
Android things
 
Is the database a solved problem?
Is the database a solved problem?Is the database a solved problem?
Is the database a solved problem?
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Sociale netværk
Sociale netværkSociale netværk
Sociale netværk
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012
 
Hadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxHadoop - the data scientist's toolbox
Hadoop - the data scientist's toolbox
 
JavaScript/Emacs integration
JavaScript/Emacs integrationJavaScript/Emacs integration
JavaScript/Emacs integration
 
Introduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software DevelopmentIntroduction to JavaScript for Modern Software Development
Introduction to JavaScript for Modern Software Development
 
Kendthed og vigtighed
Kendthed og vigtighedKendthed og vigtighed
Kendthed og vigtighed
 

Recently uploaded

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 

Recently uploaded (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 

Extending Node.js using C++

  • 1. Extending Node.js Using C++ Kenneth Geisshirt Open Source Days 2013
  • 2. About me ● Education – B.Sc. in computer science (Univ. of Copenhagen) – M.Sc. in chemistry (Univ. of Copenhagen) – Ph.D. in soft material science (Roskilde Univ.) ● Freelance writer and tech review ● Senior software developer at TightDB, Inc. – Documentation and benchmarking – Implementing language bindings
  • 3. Agenda ● What is Node.js and V8? ● C++ classes ● Wrapping classes – Setters, getters, deleters, enumerators – Anonymous functions – Exceptions – Instantiate objects ● Building extensions Codeexamples
  • 4. What is Node.js? ● Server-side JavaScript ● Based on Google V8 ● Event-driven, non-blocking I/O ● Many modules – Network, files, databases, etc. – Mostly written in JavaScript var http = require('http'); var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); var q = require('url').parse(req.url, true); res.end('<html><body>Hello '+q.query.name+'</body></html>'); }).listen(9876, "127.0.0.1");
  • 5. Google V8 ● High performance JavaScript engine – Written in C++ – Incremental garbage collector – Just-in-Time compilation (ARM, IA-32, x86_64, MIPS) – Used in Chrome and Chromium ● Classes for JavaScript types Object Array Boolean FunctionStringDateNumber
  • 6. C++ classes ● Person – firstname – lastname – birthday – to_str ● Book – add – lookup – operator [] – remove – size Files: book.hpp, book.cpp person.hpp, person.cpp main.cpp Makefile
  • 7. Wrapper classes ● Inherit from ObjectWrap ● Declaring friendships can be an advantage ● Common (static) methods: – Method Init adds class to runtime – Method New instantiates an object ● Remember that JavaScript has “funny” scope rules ● Special exception class ● Validate arguments as JavaScript isn't strongly typed
  • 8. Wrapper classes ● Inherit from ObjectWrap ● Declaring friendships can be an advantage ● Common (static) methods: – Method Init adds class to runtime – Method New instantiates an object ● Remember that JavaScript has “funny” scope rules ● Special exception class ● Validate arguments as JavaScript isn't strongly typed
  • 9. Initialize ● Method Init – Sets the class name – Sets the number of internal fields – Adds methods to runtime ● NODE_SET_PROTOTYPE_METHOD macro – Adds getter/setter/deleter/enumerator – Create a constructor (function object) Example: PersonWrap::Init and BookWrap::Init
  • 10. Arguments ● Class Arguments are in methods – An array of V8 objects ● Variable number of arguments – Length method is useful ● Typical a lot of input validation – IsString, IsArray, IsNumber, etc. ● The This() method returns the current object – You must unwrap it to get your object Example: BookWeap::Lookup
  • 11. Scope ● Methods need access to the JavaScript stack ● A HandleScope object can help you – Methods begin by creating the object – Stack allocation (local variable) ● Exit methods by closing scope – Returns a variable to the previous scope – Scope cannot be used – Garbage collector will eventually deallocate it ● Local<T> is for local (stack allocated) variables Photo by Hertje Brodersen Example: BookWrap::Length
  • 12. (V8) Exceptions ● In JavaScript, you can throw any object ● V8 implements it as a C++ class ● Five different: – RangeError, ReferenceError, SyntaxError, TypeError, Error ● You throw by returning an exception object – And it can be caught in you JavaScript program Example: BookWrap::Add
  • 13. New instance ● JavaScript programs can create new objects – Or instances of you class ● The New method is called when a new object is created – Create a wrapper object – Probably you must create a wrapped object, too – Wrap this and return it ● The constructor can easily take arguments Example: BookWrap::New
  • 14. New instance from C++ ● You can create JavaScript objects from C++ – Useful when a method returns a wrapped object ● Overload the New method – Or use another name ● The constructor (of the wrapper class) has a NewInstance method ● Pointer to wrapped object is added as internal field ● Friendship between wrapper classes is very useful Example: PersonWrap::New ×3
  • 15. Getter and setter ● JavaScript has to index operators – [] for array-like access (indexed) – . for attributes (named) ● No negative index (uint32_t) Examples: BookWrap::Getter and PersonWrap::Setter
  • 16. Deleter and Enumerator ● JavaScript's delete operator is supported by implementing a Deleter – Must return either true or false ● An enumerator makes it possible to do for ... in Example: BookWrap::Deleter and BookWrap::Enumerator
  • 17. Anonymous functions ● JavaScript programmers love anonymous functions – Functions are just an object → can be an argument ● You must set the context – JavaScript is complex – Current one is often fine ● Set up the arguments Example: BookWrap::Each
  • 18. Catching Exceptions ● JavaScript functions can throw exceptions – And you can catch them in C++ – The TryCatch class implement a handler ● Complication: – JavaScript might return an object if successful – But an exception is also an object – (the V8 tutorial is probably wrong) ● You can rethrow exceptions Example: BookWrap::Apply
  • 19. Build ● Initialize classes from init – File: funstuff_node.cpp ● Using old-school node-waf – Write a wscript file ● Newer extensions use gyp
  • 20. Where to go? ● Get my demo extension: https://github.com/kneth/FunStuff ● Node.js: http://nodejs.org/ ● JavaScript Unit Testing by Hazam Salah ● V8 classes: http://bespin.cz/~ondras/html/hierarchy.html
  • 21. Observations ● Extensions do not have to be a one-to-one mapping ● A lot of code to do input validation – JavaScript is not strongly typed! ● C++ has classes – JavaScript doesn't – Awkward for JavaScript programmers ● Node.js extension can (relative) easily be ported to Chrome ● Nodeunit is nice for unit testing