SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

ooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wengerooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wenger
Amos Wenger
 

La actualidad más candente (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 a Extending Node.js using C++

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
Asankhaya Sharma
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
Terry Yoast
 

Similar a 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
 
Object oriented programming with java pdf
Object oriented programming with java pdfObject oriented programming with java pdf
Object oriented programming with java pdf
 
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
 

Más de Kenneth Geisshirt

Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012
Kenneth Geisshirt
 
JavaScript/Emacs integration
JavaScript/Emacs integrationJavaScript/Emacs integration
JavaScript/Emacs integration
Kenneth Geisshirt
 

Más de 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
 

Último

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Último (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

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