SlideShare a Scribd company logo
Server side JavaScript: going all the way #rejectjs 29.09.11
/me #startups #akshell #ringojs #moscowjs #dailyjs
 
Node.js Ideal use cases Real time apps, infrastructure duct tape Badly suited for CRUD, command line tools, CPU heavy loads Easy to get started with Difficult to get into production
 
Akshell NarwhalJS RingoJS Wakanda GPSEE v8cgi
ServerJS Fragmentation
Sync vs. Async
 
“ async style is kicking sync style's ass”
 
sync is “on top of” async –  a higher level of abstraction
Sync   vs.  Async   function add(callback) { http.get(url1, function(response1) { var part1 = response1.data; http.get(url2, function(response2) { var part2 = response2.data; callback(part1 + part2); } } }
Sync  vs.   Async http.get(url1).data + http.get(url2).data
Interoperability Pure JavaScript modules run anywhere Templating, parsing, formatting, encoding Anything doing I/O exposes sync or async API Defines the interface exposed by higher level packages
 
CommonJS /1 Assert Console System/1.0
CommonJS /2 Binary/B IO/A Filesystem/A JSGI 0.3 HTTP Client /A Sockets/A Subprocess
common-node Implements  synchronous  CommonJS proposals using node-fibers  Traceur to support latest language features Bridges the gap between platforms, sync and async
What it's good for?
everything!
What's it  actually  good for? Business logic Lots of state, fine grained error handling CRUD Java, Rails, PHP, Python Command line tools Cross platform portability
On Threads & Fibers “ Threads suck”  - Brendan Eich, creator of JavaScript “ Fibers introduce interleaving hazards — Any function call can cause a yield and then your closure invariants *may be* broken.” - Kris Kowal, creator of CommonJS/Modules
Concurrency in JavaScript “ You shouldn’t think that event-based concurrency eliminates synchronization, or shared memory, or anything other than preemption” - Sam Tobin-Hochstadt, member of the Ecma TC39 committee on JavaScript
fibers /1 Co routine implementation using libcoro  Co-operative multitasking Implicit synchronization
fibers /2 Not a fork or a hack of Node No wrapper script required V8 Context and 64KB stack per fiber Will run on Windows
Node.js process [ closure closure t  ->
RingoJS (0.8) process thread  stack process thread  stack t  ->
Common Node (fibers) process fiber stack fiber stack [ t  ->
Comparison Node.js Common Node RingoJS Process Count Single Single Multiple State Closure Fiber Stack Thread Stack Multitasking User (co-op) Library (co-op) OS (pre-empt) Memory Usage Low Low High “ Jitter” High High Low
Internals - sleep exports.sleep = function(milliseconds) { var fiber = Fiber.current; setTimeout(function() { fiber.run(); }, milliseconds); yield(); } ;
Internals – HttpClient /1 var req = http.request(options, function(r) { fiber.run(r); }); req.on('error', function(error) { fiber.run(error); }); this.guts.body.forEach(function(block) { req.write(block.buffer || block); }); req.end();
Internals – HttpClient /2 var result = yield(); if(result instanceof Error) throw new Error(result.message); return { status: result.statusCode, headers: result.headers, body: new Stream(result) };
Internals - IO // on 'data', 'end', 'error' // pause when draining var listeners = attach(this.stream); var data = yield(); detach(this.stream, listeners);
Examples
JSGI exports.app = function(request) { return { status: 200, headers: {}, body: ['Hello World!']  // openRaw(module.filename) }; };
Spawn & Sleep exports.app = function(request) { spawn(function() { sleep(10000); console.log('Hello Server!'); }); return { status: 200, headers: {}, body: ['Hello Client!'] }; };
HTTP Proxy var HttpClient = require('httpclient').HttpClient; exports.app = function(req) { req.url = 'http://nodejs.org'; return new HttpClient(req).finish(); };
Twitter Streaming /1 var stream = new TextStream(   new HttpClient({ method:  'POST', url:  '...', headers: {} body: ['track='+system.args[4]], timeout: 10000 }).finish().body);
Twitter Streaming /2 var line; while(true) { line = stream.readLine(); if(!line.length) break; if(line.length > 1) { var message = JSON.parse(line); console.log(message.text); } }
Telnet Chat /1 var socket = require('socket'); var server = new socket.Socket();  var clients = [], client; server.bind('localhost', 23);
Telnet Chat /2 while(true) { clients.push(client = server.accept().getStream()); spawn(function() {   var stream = client, line; while((line = stream.read(null)).length) { clients.forEach(function(c) { if(stream != c) c.write(line); }); } clients.splice(clients.indexOf(stream), 1); }); }
Demo telnet 10.0.0.97
Benchmarks ab -n 50000 -c 50
hello-world exports.app = function() { return { status: 200, headers: { 'Content-Type': 'text/plain' }, body: ['Hello World!\n'] }; };
 
string-alloc exports.app = function(request) { for( var i = 1; i <= 50; i++) b.decodeToString(&quot;ascii&quot;); return { status: 200, headers: {}, body: [b] }; };
 
parse-json exports.app = function(request) { JSON.parse(json); return { status: 200, headers: {}, body: [json] }; };
 
static-file exports.app = function() { return {  status: 200,  headers: {},  body:  openRaw('../README.md') }; };
 
set-timeout exports.app = function() { sleep(100); return { status: 200, headers: {}, body: [] }; };
 
Throughput
SyncJS Fragmentation
Road map common-utils tests in separate project narhwal-mongodb fork hns/stick fork higher level packages (see project wiki)
Contributing Google  “ common node ” github.com/olegp/common-node/ npm -g install common-node
Thank you! @olegpodsechin

More Related Content

PPT
JS everywhere 2011
KEY
Streams are Awesome - (Node.js) TimesOpen Sep 2012
PDF
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
PDF
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
KEY
Introduction to node.js
PPTX
JavaScript Engines and Event Loop
PDF
Non-blocking I/O, Event loops and node.js
PPTX
How NOT to write in Node.js
JS everywhere 2011
Streams are Awesome - (Node.js) TimesOpen Sep 2012
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Introduction to node.js
JavaScript Engines and Event Loop
Non-blocking I/O, Event loops and node.js
How NOT to write in Node.js

What's hot (20)

PDF
Callbacks and control flow in Node js
PDF
Deep Dive async/await in Unity with UniTask(EN)
PPTX
PPTX
Avoiding Callback Hell with Async.js
PDF
Node.js streaming csv downloads proxy
PDF
用 Go 語言打造多台機器 Scale 架構
PDF
Non Blocking I/O for Everyone with RxJava
PPTX
Nodejs intro
PPTX
Node.js System: The Approach
PPTX
Microsoft HPC - Kivanc Ozuolmez - Public Content
PPTX
Bucks County Tech Meetup: node.js introduction
PDF
Job Queue in Golang
PPT
Async programming on NET
PDF
CLS & asyncListener: asynchronous observability for Node.js
PDF
"Swoole: double troubles in c", Alexandr Vronskiy
PPT
Reactive programming with examples
PDF
KrakenJS
PPTX
ECMAScript 6 and the Node Driver
PPTX
Javascript asynchronous
PDF
Odoo Performance Limits
Callbacks and control flow in Node js
Deep Dive async/await in Unity with UniTask(EN)
Avoiding Callback Hell with Async.js
Node.js streaming csv downloads proxy
用 Go 語言打造多台機器 Scale 架構
Non Blocking I/O for Everyone with RxJava
Nodejs intro
Node.js System: The Approach
Microsoft HPC - Kivanc Ozuolmez - Public Content
Bucks County Tech Meetup: node.js introduction
Job Queue in Golang
Async programming on NET
CLS & asyncListener: asynchronous observability for Node.js
"Swoole: double troubles in c", Alexandr Vronskiy
Reactive programming with examples
KrakenJS
ECMAScript 6 and the Node Driver
Javascript asynchronous
Odoo Performance Limits
Ad

Viewers also liked (10)

PDF
NodeJS for Beginner
PDF
Why SaaS (in Helsinki)?
PPTX
Chat server nitish nagar
PPTX
Telnet & SSH Configuration
PPT
PPT
Telnet
PDF
TELNET Protocol
PPT
Presentation on telnet
PDF
Nodejs Explained with Examples
PDF
Getting started with node JS
NodeJS for Beginner
Why SaaS (in Helsinki)?
Chat server nitish nagar
Telnet & SSH Configuration
Telnet
TELNET Protocol
Presentation on telnet
Nodejs Explained with Examples
Getting started with node JS
Ad

Similar to Server side JavaScript: going all the way (20)

KEY
Writing robust Node.js applications
PDF
Node.js - async for the rest of us.
PPT
Node js presentation
PDF
Presto anatomy
PDF
Future Decoded - Node.js per sviluppatori .NET
PPTX
NodeJS
PPTX
introduction to node.js
PDF
Original slides from Ryan Dahl's NodeJs intro talk
PPTX
The Road To Reactive with RxJava JEEConf 2016
PDF
[245] presto 내부구조 파헤치기
PPTX
Event-driven IO server-side JavaScript environment based on V8 Engine
PPT
Node.js: CAMTA Presentation
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
PDF
Porting a Streaming Pipeline from Scala to Rust
PPTX
Node.js
PDF
soft-shake.ch - Hands on Node.js
PPTX
JavaScript Multithread or Single Thread.pptx
ODP
Node js
PDF
Introduction to Node.js
PDF
Node.js for Rubists
Writing robust Node.js applications
Node.js - async for the rest of us.
Node js presentation
Presto anatomy
Future Decoded - Node.js per sviluppatori .NET
NodeJS
introduction to node.js
Original slides from Ryan Dahl's NodeJs intro talk
The Road To Reactive with RxJava JEEConf 2016
[245] presto 내부구조 파헤치기
Event-driven IO server-side JavaScript environment based on V8 Engine
Node.js: CAMTA Presentation
Workshop 4: NodeJS. Express Framework & MongoDB.
Porting a Streaming Pipeline from Scala to Rust
Node.js
soft-shake.ch - Hands on Node.js
JavaScript Multithread or Single Thread.pptx
Node js
Introduction to Node.js
Node.js for Rubists

More from Oleg Podsechin (12)

PDF
Staying safe in the cloud
PDF
Tips from angular js users anonymous
PPT
AngularJS - the folly of choice
PDF
Lean and mean MongoDB
PPT
PPT
What every developer can learn from startups
PPT
Current State of Server Side JavaScript
PPT
On Platforms
PPT
Common Node
PPT
The future of server side JavaScript
PPT
PPT
Grid and Cloud Computing Intro
Staying safe in the cloud
Tips from angular js users anonymous
AngularJS - the folly of choice
Lean and mean MongoDB
What every developer can learn from startups
Current State of Server Side JavaScript
On Platforms
Common Node
The future of server side JavaScript
Grid and Cloud Computing Intro

Recently uploaded (20)

PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
Modernizing your data center with Dell and AMD
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
The AUB Centre for AI in Media Proposal.docx
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
Modernizing your data center with Dell and AMD
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
GamePlan Trading System Review: Professional Trader's Honest Take
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Understanding_Digital_Forensics_Presentation.pptx
Network Security Unit 5.pdf for BCA BBA.
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
20250228 LYD VKU AI Blended-Learning.pptx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
Approach and Philosophy of On baking technology
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...

Server side JavaScript: going all the way

  • 1. Server side JavaScript: going all the way #rejectjs 29.09.11
  • 2. /me #startups #akshell #ringojs #moscowjs #dailyjs
  • 3.  
  • 4. Node.js Ideal use cases Real time apps, infrastructure duct tape Badly suited for CRUD, command line tools, CPU heavy loads Easy to get started with Difficult to get into production
  • 5.  
  • 6. Akshell NarwhalJS RingoJS Wakanda GPSEE v8cgi
  • 9.  
  • 10. “ async style is kicking sync style's ass”
  • 11.  
  • 12. sync is “on top of” async – a higher level of abstraction
  • 13. Sync vs. Async function add(callback) { http.get(url1, function(response1) { var part1 = response1.data; http.get(url2, function(response2) { var part2 = response2.data; callback(part1 + part2); } } }
  • 14. Sync vs. Async http.get(url1).data + http.get(url2).data
  • 15. Interoperability Pure JavaScript modules run anywhere Templating, parsing, formatting, encoding Anything doing I/O exposes sync or async API Defines the interface exposed by higher level packages
  • 16.  
  • 17. CommonJS /1 Assert Console System/1.0
  • 18. CommonJS /2 Binary/B IO/A Filesystem/A JSGI 0.3 HTTP Client /A Sockets/A Subprocess
  • 19. common-node Implements synchronous CommonJS proposals using node-fibers Traceur to support latest language features Bridges the gap between platforms, sync and async
  • 22. What's it actually good for? Business logic Lots of state, fine grained error handling CRUD Java, Rails, PHP, Python Command line tools Cross platform portability
  • 23. On Threads & Fibers “ Threads suck” - Brendan Eich, creator of JavaScript “ Fibers introduce interleaving hazards — Any function call can cause a yield and then your closure invariants *may be* broken.” - Kris Kowal, creator of CommonJS/Modules
  • 24. Concurrency in JavaScript “ You shouldn’t think that event-based concurrency eliminates synchronization, or shared memory, or anything other than preemption” - Sam Tobin-Hochstadt, member of the Ecma TC39 committee on JavaScript
  • 25. fibers /1 Co routine implementation using libcoro Co-operative multitasking Implicit synchronization
  • 26. fibers /2 Not a fork or a hack of Node No wrapper script required V8 Context and 64KB stack per fiber Will run on Windows
  • 27. Node.js process [ closure closure t ->
  • 28. RingoJS (0.8) process thread stack process thread stack t ->
  • 29. Common Node (fibers) process fiber stack fiber stack [ t ->
  • 30. Comparison Node.js Common Node RingoJS Process Count Single Single Multiple State Closure Fiber Stack Thread Stack Multitasking User (co-op) Library (co-op) OS (pre-empt) Memory Usage Low Low High “ Jitter” High High Low
  • 31. Internals - sleep exports.sleep = function(milliseconds) { var fiber = Fiber.current; setTimeout(function() { fiber.run(); }, milliseconds); yield(); } ;
  • 32. Internals – HttpClient /1 var req = http.request(options, function(r) { fiber.run(r); }); req.on('error', function(error) { fiber.run(error); }); this.guts.body.forEach(function(block) { req.write(block.buffer || block); }); req.end();
  • 33. Internals – HttpClient /2 var result = yield(); if(result instanceof Error) throw new Error(result.message); return { status: result.statusCode, headers: result.headers, body: new Stream(result) };
  • 34. Internals - IO // on 'data', 'end', 'error' // pause when draining var listeners = attach(this.stream); var data = yield(); detach(this.stream, listeners);
  • 36. JSGI exports.app = function(request) { return { status: 200, headers: {}, body: ['Hello World!'] // openRaw(module.filename) }; };
  • 37. Spawn & Sleep exports.app = function(request) { spawn(function() { sleep(10000); console.log('Hello Server!'); }); return { status: 200, headers: {}, body: ['Hello Client!'] }; };
  • 38. HTTP Proxy var HttpClient = require('httpclient').HttpClient; exports.app = function(req) { req.url = 'http://nodejs.org'; return new HttpClient(req).finish(); };
  • 39. Twitter Streaming /1 var stream = new TextStream( new HttpClient({ method: 'POST', url: '...', headers: {} body: ['track='+system.args[4]], timeout: 10000 }).finish().body);
  • 40. Twitter Streaming /2 var line; while(true) { line = stream.readLine(); if(!line.length) break; if(line.length > 1) { var message = JSON.parse(line); console.log(message.text); } }
  • 41. Telnet Chat /1 var socket = require('socket'); var server = new socket.Socket(); var clients = [], client; server.bind('localhost', 23);
  • 42. Telnet Chat /2 while(true) { clients.push(client = server.accept().getStream()); spawn(function() { var stream = client, line; while((line = stream.read(null)).length) { clients.forEach(function(c) { if(stream != c) c.write(line); }); } clients.splice(clients.indexOf(stream), 1); }); }
  • 44. Benchmarks ab -n 50000 -c 50
  • 45. hello-world exports.app = function() { return { status: 200, headers: { 'Content-Type': 'text/plain' }, body: ['Hello World!\n'] }; };
  • 46.  
  • 47. string-alloc exports.app = function(request) { for( var i = 1; i <= 50; i++) b.decodeToString(&quot;ascii&quot;); return { status: 200, headers: {}, body: [b] }; };
  • 48.  
  • 49. parse-json exports.app = function(request) { JSON.parse(json); return { status: 200, headers: {}, body: [json] }; };
  • 50.  
  • 51. static-file exports.app = function() { return { status: 200, headers: {}, body: openRaw('../README.md') }; };
  • 52.  
  • 53. set-timeout exports.app = function() { sleep(100); return { status: 200, headers: {}, body: [] }; };
  • 54.  
  • 57. Road map common-utils tests in separate project narhwal-mongodb fork hns/stick fork higher level packages (see project wiki)
  • 58. Contributing Google “ common node ” github.com/olegp/common-node/ npm -g install common-node