The document outlines an introduction to Node.js workshop covering topics like installation, the REPL, core components, modules, NPM, and building applications. It provides information on installing Node.js, using the interactive REPL shell, key internal components like V8 and libuv, internal and custom modules, the module system, and the NPM package manager. Examples are given for various concepts like using the REPL, accessing V8 fast properties, implementing and using custom modules, and NPM commands.
Make container without_docker_6-overlay-network_1 Sam Kim
분산환경에서 컨테이너 간의 통신은 어떻게 이루어 지는 것일까요? 3,4편에서는 호스트 안에 가상네트워크를 만들어보았습니다. 6편에서는 이를 바탕으로 분산환경에서 호스트 간에 가상 네트워크로 통신이 가능하도록 만들어 봅니다. 이 방법은 실제 쿠버네티스 flannel 등의 CNI에서 사용하고 있는 vxlan 기반의 오버레이 네트워크 구성을 다룹니다.
Make container without_docker_6-overlay-network_1 Sam Kim
분산환경에서 컨테이너 간의 통신은 어떻게 이루어 지는 것일까요? 3,4편에서는 호스트 안에 가상네트워크를 만들어보았습니다. 6편에서는 이를 바탕으로 분산환경에서 호스트 간에 가상 네트워크로 통신이 가능하도록 만들어 봅니다. 이 방법은 실제 쿠버네티스 flannel 등의 CNI에서 사용하고 있는 vxlan 기반의 오버레이 네트워크 구성을 다룹니다.
Any piece of software can only be as good as its foundations. To rise as high as we need it to, we decided eZ Publish needed new ones. Today, we will tell you how these are architectured, and give you a glimpse of their possibilities.
Introduction to node.js by Ran Mizrahi @ Reversim SummitRan Mizrahi
Node.js is a platform built on Chrome V8 javascript runtime engine for building fast and scalable, non-blocking, real-time and network applications. In this session I'll introduce you to node.js and developing large code bases using it. We'll cover the following aspects:
* What is node.js?
* Apache vs. Nginx performance (One thread per connection vs. event loop) and what it has to do with node.js.
* Why node was written in Javascript?
* Main tools and frameworks (Express, socket.io, mongoose etc.)
* TDD/BDD with node.js using mocha and Expect.js
Describes what is lightweight virtualization and containers, and the low-level mechanisms in the Linux kernel that it relies on: namespaces, cgroups. It also gives details on AUFS. Those component together are the key to understanding how modern systems like Docker (http://www.docker.io/) work.
OSDC 2016 - Interesting things you can do with ZFS by Allan Jude&Benedict Reu...NETWAYS
ZFS is the next generation filesystem originally developed at Sun Microsystems. Available under the CDDL, it uniquely combines volume manager and filesystem into a powerful storage management solution for Unix systems. Regardless of big or small storage requirements. ZFS offers features, for free, that are usually found only in costly enterprise storage solutions. This talk will introduce ZFS and give an overview of its features like snapshots and rollback, compression, deduplication as well as replication. We will demonstrate how these features can make a difference in the datacenter, giving administrators the power and flexibility to adapt to changing storage requirements.
Real world examples of ZFS being used in production for video streaming, virtualization, archival, and research are shown to illustrate the concepts. The talk is intended for people considering ZFS for their data storage needs and those who are interested in the features ZFS provides.
De vuelta al pasado con SQL y stored proceduresNorman Clarke
El uso de stored procedures está muy difundido entre los administradores de bases de datos como una forma de encapsular la lógica de datos de las aplicaciones. La comunidad de desarrolladores web, sin embargo, nunca los adoptó plenamente porque siempre ha tenido dudas acerca de su portabilidad y mantenibilidad, además de una antipatía generalizada por SQL.
De todos modos, la alternativa que se utiliza actualmente, la dupla abstracción de base de datos-ORM, también tiene sus propios problemas: baja performance, subutilización de las funciones avanzadas de bases de datos, y sintaxis de queries ad-hoc que terminan siendo más complicadas que el propio SQL.
La creciente popularidad de las bases de datos NoSQL pone de manifiesto que los desarrolladores web contemporáneos están de nuevo dispuestos a considerar librerías de bases de datos específicas del vendedor para el desarrollo de aplicaciones. Entonces veamos qué es lo que tiene para ofrecernos un vendedor en particular: PostgreSQL.
En esta charla voy a demostrar que crear una API basada en una mezcla de objetos Ruby sencillos y stored procedures de Postgres puede ser una opción muy convincente como sustituto de ORM.
Mastering ElasticSearch with Ruby and TireLuca Bonmassar
A tutorial on what is ElasticSearch and how to use it effectively in a real project.
The talk discusses how to integrate a search experience in an existing application, showing all the steps from downloading&configuring elastic search, to building the UI and wire the search logic (in a Rails application).
The talk was presented at RubyConf 2013.
Symfony2 and MongoDB - MidwestPHP 2013 Pablo Godel
In this talk we will see how to use MongoDB in Symfony2 projects to speed up the development of web applications. We will give an introduction of MongoDB as a NoSQL database server and look at the options on how to work with it from Symfony2 and PHP applications.
Frameworks wie Next.js und Nuxt versuchen, Client und Server wieder näher zusammenzubringen und setzen dabei auf die großen SPA-Frameworks React und Vue. Die leichtgewichtige Bibliothek htmx dagegen versucht, das gleiche Ziel auf ganz andere Weise zu erreichen. Muss es denn immer eine SPA sein? Reicht nicht auch in vielen Fällen deutlich weniger Overhead? Wir haben schließlich HTML als Strukturelement und CSS für das gute Aussehen. Genau diesen Ansatz greift htmx auf und erweitert die Fähigkeiten der HTML-Struktur. Serverkommunikation und Eventhandling erreichen mit dieser Bibliothek eine ganz neue Dimension.
Aber was bedeutet das für unsere tägliche Arbeit? Setzen wir in Zukunft alle neuen Applikationen nur noch mit htmx um, oder migrieren wir unsere Vue-Codebasis auf htmx? Diesen und vielen weiteren Fragen widmen wir uns in diesem Vortrag, nicht nur in der Theorie, sondern auch am praktischen Beispiel.
Angular ist die Komplettlösung für die Umsetzung von Webapplikationen im Frontend. Ein so umfassendes Werkzeug hat allerdings auch seine Schattenseiten: Die Einstiegshürde ist relativ hoch. Dieser Vortrag stellt die wichtigsten Elemente des Frameworks wie Komponenten, Direktiven und Services vor. In einem praktischen Beispiel werden die verschiedenen Elemente von Angular Schritt für Schritt zu einer kompletten Applikation zusammengefügt. Damit lernen Sie nicht nur die Elemente des Frameworks kennen, sondern gleichzeitig die wichtigsten Architekturpatterns und zahlreiche Best Practices.
Any piece of software can only be as good as its foundations. To rise as high as we need it to, we decided eZ Publish needed new ones. Today, we will tell you how these are architectured, and give you a glimpse of their possibilities.
Introduction to node.js by Ran Mizrahi @ Reversim SummitRan Mizrahi
Node.js is a platform built on Chrome V8 javascript runtime engine for building fast and scalable, non-blocking, real-time and network applications. In this session I'll introduce you to node.js and developing large code bases using it. We'll cover the following aspects:
* What is node.js?
* Apache vs. Nginx performance (One thread per connection vs. event loop) and what it has to do with node.js.
* Why node was written in Javascript?
* Main tools and frameworks (Express, socket.io, mongoose etc.)
* TDD/BDD with node.js using mocha and Expect.js
Describes what is lightweight virtualization and containers, and the low-level mechanisms in the Linux kernel that it relies on: namespaces, cgroups. It also gives details on AUFS. Those component together are the key to understanding how modern systems like Docker (http://www.docker.io/) work.
OSDC 2016 - Interesting things you can do with ZFS by Allan Jude&Benedict Reu...NETWAYS
ZFS is the next generation filesystem originally developed at Sun Microsystems. Available under the CDDL, it uniquely combines volume manager and filesystem into a powerful storage management solution for Unix systems. Regardless of big or small storage requirements. ZFS offers features, for free, that are usually found only in costly enterprise storage solutions. This talk will introduce ZFS and give an overview of its features like snapshots and rollback, compression, deduplication as well as replication. We will demonstrate how these features can make a difference in the datacenter, giving administrators the power and flexibility to adapt to changing storage requirements.
Real world examples of ZFS being used in production for video streaming, virtualization, archival, and research are shown to illustrate the concepts. The talk is intended for people considering ZFS for their data storage needs and those who are interested in the features ZFS provides.
De vuelta al pasado con SQL y stored proceduresNorman Clarke
El uso de stored procedures está muy difundido entre los administradores de bases de datos como una forma de encapsular la lógica de datos de las aplicaciones. La comunidad de desarrolladores web, sin embargo, nunca los adoptó plenamente porque siempre ha tenido dudas acerca de su portabilidad y mantenibilidad, además de una antipatía generalizada por SQL.
De todos modos, la alternativa que se utiliza actualmente, la dupla abstracción de base de datos-ORM, también tiene sus propios problemas: baja performance, subutilización de las funciones avanzadas de bases de datos, y sintaxis de queries ad-hoc que terminan siendo más complicadas que el propio SQL.
La creciente popularidad de las bases de datos NoSQL pone de manifiesto que los desarrolladores web contemporáneos están de nuevo dispuestos a considerar librerías de bases de datos específicas del vendedor para el desarrollo de aplicaciones. Entonces veamos qué es lo que tiene para ofrecernos un vendedor en particular: PostgreSQL.
En esta charla voy a demostrar que crear una API basada en una mezcla de objetos Ruby sencillos y stored procedures de Postgres puede ser una opción muy convincente como sustituto de ORM.
Mastering ElasticSearch with Ruby and TireLuca Bonmassar
A tutorial on what is ElasticSearch and how to use it effectively in a real project.
The talk discusses how to integrate a search experience in an existing application, showing all the steps from downloading&configuring elastic search, to building the UI and wire the search logic (in a Rails application).
The talk was presented at RubyConf 2013.
Symfony2 and MongoDB - MidwestPHP 2013 Pablo Godel
In this talk we will see how to use MongoDB in Symfony2 projects to speed up the development of web applications. We will give an introduction of MongoDB as a NoSQL database server and look at the options on how to work with it from Symfony2 and PHP applications.
Frameworks wie Next.js und Nuxt versuchen, Client und Server wieder näher zusammenzubringen und setzen dabei auf die großen SPA-Frameworks React und Vue. Die leichtgewichtige Bibliothek htmx dagegen versucht, das gleiche Ziel auf ganz andere Weise zu erreichen. Muss es denn immer eine SPA sein? Reicht nicht auch in vielen Fällen deutlich weniger Overhead? Wir haben schließlich HTML als Strukturelement und CSS für das gute Aussehen. Genau diesen Ansatz greift htmx auf und erweitert die Fähigkeiten der HTML-Struktur. Serverkommunikation und Eventhandling erreichen mit dieser Bibliothek eine ganz neue Dimension.
Aber was bedeutet das für unsere tägliche Arbeit? Setzen wir in Zukunft alle neuen Applikationen nur noch mit htmx um, oder migrieren wir unsere Vue-Codebasis auf htmx? Diesen und vielen weiteren Fragen widmen wir uns in diesem Vortrag, nicht nur in der Theorie, sondern auch am praktischen Beispiel.
Angular ist die Komplettlösung für die Umsetzung von Webapplikationen im Frontend. Ein so umfassendes Werkzeug hat allerdings auch seine Schattenseiten: Die Einstiegshürde ist relativ hoch. Dieser Vortrag stellt die wichtigsten Elemente des Frameworks wie Komponenten, Direktiven und Services vor. In einem praktischen Beispiel werden die verschiedenen Elemente von Angular Schritt für Schritt zu einer kompletten Applikation zusammengefügt. Damit lernen Sie nicht nur die Elemente des Frameworks kennen, sondern gleichzeitig die wichtigsten Architekturpatterns und zahlreiche Best Practices.
Node.js is a lightweight but yet capable platform for creating powerful web applications. The core of Node.js is kept small and restricted to a limited functionality that is extended by a vast ecosystem. With the right combination of packages you are able to build full-featured web applications. There is nearly no limit in features starting with simple problems such as authentication or logging over web interfaces with REST or GraphQL to a whole application based on a microservices architecture. In this talk I will introduce you to some commonly used packages and show you how to use them by example.
Node.js and microservices go hand in hand. This comes mainly from the design of Node.js. It is a specialised small platform with an enormous package environment. The NPM ecosystem provides a lot of packages you can use to build your microservice. The two most popular frameworks for this job are Express and Seneca. In this talk I will show you how you can communicate synchronously and asynchronously with your microservices and how easy it is to put your Node.js application into a docker container.
Nobody likes to wait for web pages to load in the browser. The longer it takes, the more dissatisfied the users become. Slow web pages lead to a higher bounce rate and the loss of customers. To solve this kind of problems can be very hard sometimes. Before you even start to optimise your page, you have to understand the workflows a browser performs in order to display a page on the screen. In this talk you will get some insights in the critical rendering path and the javascript engine of your browser that help you to find performance problems and solve them. I will show you also some tools and best practices that make your life easier when it comes to performance.
Lange Wartezeiten und mangelnde Responsivität unserer Webapplikation führen zu unzufriedenen Benutzern, was sich in hohen Absprungraten und Abwanderung zur Konkurrenz oder einfach der Weigerung, die Applikation zu verwenden, niederschlägt. Das Problem einer langsamen Applikation lässt sich jedoch leider nicht ganz so einfach lösen. Wichtig für eine nachhaltige Lösung ist das Verständnis der Abläufe im Browser. Aus diesem Grund beschäftigen wir uns hier mit Konzepten wie dem Critical Rendering Path und einigen Charakteristiken der JavaScript-Engines. Im Zuge dieses Vortrags werden einige der häufigsten Problemstellungen von Webapplikationen analysiert und Lösungsansätze und Best Practices zur Behebung der Performanceprobleme vorgestellt.
Features einer Applikation werden häufig implementiert, weil die Verantwortlichen vermuten, dass diese Funktionalitäten einen Mehrwert für die Benutzer der Applikation bieten. Je nach Umfang wird mehr oder weniger Geld investiert. Ohne weitere Unterstützung sind und bleiben es jedoch Vermutungen. Eine bessere Lösung bieten hier A/B-Tests. Features werden kostengünstig in einer oder mehreren Varianten umgesetzt und mit einer Kontrollimplementierung verglichen. Die Umsetzung, die sich als die beste herausstellt, wird überarbeitet und bleibt in der Applikation erhalten. Diese Vorgehensweise lässt sich sehr gut in node.js-Applikationen integrieren. Mithilfe von A/B-Tests können Sie Ihre Applikation an den Anforderungen Ihrer Benutzer ausrichten.
Eine Sammlung von Best Practices für Applikationen mit AngularJS. Der Vortrag stellt Strukturen und Konventionen vor, mit denen sich auch umfangreiche Applikationen wartbar und erweiterbar halten lassen.
Mein Vortrag auf der EnterJS 2015 über Sicherheit in Node.js Applikationen. Es werden verschiedene Angriffsvektoren vorgestellt und wie man ihnen begegnen kann.
Typescript zur Applikationsentwicklung nutzen. Hier werden die wichtigsten Features der Sprache kurz vorgestellt und am konkreten Beispiel deren Einsatz gezeigt.
Testgetriebene Entwicklung mit Jasmine und Karma hat sich mittlerweile schon als defacto-Standard etabliert. Routinen ohne Abhängigkeiten lassen sich damit ohne Probleme testen. Die Schwierigkeiten beginnen jedoch schon, wenn es um die Auflösung von Abhängigkeiten geht. In diesem Vortrag werden verschiedene Strategien und Werkzeuge vorgestellt, mit denen Abhängigkeiten zu Objekten und Funktionen oder zum Server abgedeckt werden können. Aber nicht nur Abhängigkeiten stellen Schwierigkeiten bei der testgetriebenen Entwicklung dar, auch der Umgang mit Fixtures ist bei der testgetriebenen Entwicklung mit JavaScript relevant. Abgerundet wird dieser Vortrag mit einigen Best Practices für die testgetriebenen Entwicklung mit JavaScript.
Warum ECMAScript 6 die Welt ein Stückchen besser machtSebastian Springer
Wo die Neuerungen von ECMAScript 5 recht unspektakulär waren, sind die Features des neuen Sprachstandards umso interessanter. ECMAScript 6 versucht einige Anforderungen zu erfüllen, mit denen man als JavaScript-Entwickler täglich konfrontiert ist. Klassische Beispiele sind hier Promises zum Umgang mit asynchronen Funktionen, ein Module Loader zur Strukturierung der Applikation, Generatoren und Iteratoren oder aber ein neuer Gültigkeitsbereich für Variablen. Aber nicht nur große Änderungen, sondern auch sinnvolle Erweiterungen bestehender Objekte wie String und Array halten mit dem neuen Standard Einzug in den Browser. Problematisch wird die Situation jedoch, wenn man in den Genuss verschiedener Features kommen möchte, die aktuell noch von keinem Browser unterstützt werden. Hier schafft Traceur, der ECMAScript-6-Compiler von Google, Abhilfe.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
15. REPL
$ node
> for (var i = 0; i < 3; i++) {
... console.log(i);
... }
0
1
2
undefined
>
Monday, March 11, 13
16. REPL
.break Bricht ein Multiline Statement ab
.clear Zurücksetzen + .break (CTRL + C)
.exit Beendet die aktuelle Shell (CTRL + D)
.help Liste der Befehle
.save Speichert die aktuelle Session
.load Lädt eine gespeicherte Session
Monday, March 11, 13
28. V8 - GARBAGE COLLECTION
• Programmausführung wird angehalten
• Es wird nur ein Teil des Object Heaps geprüft
• V8 kennt alle Objekte und Pointer im Speicher
Monday, March 11, 13
29. KERNKOMPONENTEN
Standard Library
Node Bindings
V8 libuv
Eventloop async I/O
libev + libeio IOCP
Monday, March 11, 13
33. X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
X X X
Monday, March 11, 13
34. APPLIKATIONEN IN NODE.JS
var Star = function () {
this.name = 'X',
this.height = 20,
this.step = 2;
};
Star.prototype.top = function() {
...
};
Star.prototype.print = function () {
console.log(this.top().join('n'));
console.log(this.middle());
console.log(this.bottom().join('n'));
}
...
var star = new Star();
star.print();
Monday, March 11, 13
42. EIGENE MODULE
• OH: “Wenn ich mir das Zeug, das in Node programmiert
wurde, so ansehe, sieht das aus wie PHP3. Einfach von oben
nach unten, alles in einer Datei”
• Liegen in einer separaten Datei
• Exportieren Klassen, Objekte oder Funktionen
• Können an anderer Stelle eingebunden werden
Monday, March 11, 13
43. EIGENE MODULE
validator.js
exports.email = function (email) {
var regex = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/,
result = regex.exec(email);
if (result) {
return true;
}
return false;
};
Monday, March 11, 13
44. EIGENE MODULE
validator.js
exports.email = function (email) {
var regex = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/,
result = regex.exec(email);
if (result) {
return true;
}
return false;
};
Monday, March 11, 13
45. VERWENDUNG EIGENER
MODULE
modules.js
var validator = require('./validator.js'),
mail = ['sebastian.springer@mayflower.de', 'Invalid Address'];
for (var i = 0; i < mail.length; i++) {
if (validator.email(mail[i])) {
console.log((i + 1) + '. Mailadresse ist gültig');
} else {
console.log((i + 1) + '. Mailadresse ist ungültig');
}
}
Monday, March 11, 13
46. VERWENDUNG EIGENER
MODULE
modules.js
var validator = require('./validator.js'),
mail = ['sebastian.springer@mayflower.de', 'Invalid Address'];
for (var i = 0; i < mail.length; i++) {
if (validator.email(mail[i])) {
console.log((i + 1) + '. Mailadresse ist gültig');
} else {
console.log((i + 1) + '. Mailadresse ist ungültig');
}
}
Monday, March 11, 13
47. EIGENE MODULE
$ node modules.js
1. Mailadresse ist gültig
2. Mailadresse ist ungültig
Monday, March 11, 13
49. NPM
• Node Package Manager (von Isaac Schlueter)
• Bestandteil von Node.js seit 0.6.3
• https://github.com/isaacs/npm
Monday, March 11, 13
50. NPM - REPO
• Hier kommen die Pakete für das npm-Kommando her
• https://npmjs.org/
• Aktuell über 24.000 Pakete
• https://registry.npmjs.org/-/all/
Monday, March 11, 13
52. NPM SEARCH
$ npm se mysql
npm http GET https://registry.npmjs.org/-/all/since?stale=update_aft...
npm http 200 https://registry.npmjs.org/-/all/since?stale=update_aft...
NAME DESCRIPTION AUTHOR DATE KEYWORDS...
Accessor_M... A MySQL database wrapper... =bu 2012-1... mysql ac...
any-db Database-agnostic connec... =grncdr 2013-0... mysql po...
autodafe mvc framework for node w... =jifeon 2012-1... mvc fram...
backbone-m... A sync module for Backbo... =ccowan 2012-1...
caminte ORM for every database: ... =biggor 2013-0... caminte ...
connect-my... a MySQL session store fo... =nathan 2012-0...
connect-my... A MySQL session store fo... =daniel 2011-0...
cormo ORM framework for Node.j... =croqui 2013-0... orm mong...
Monday, March 11, 13
53. NPM INSTALL
$ npm in mysql
npm http GET https://registry.npmjs.org/mysql
npm http 200 https://registry.npmjs.org/mysql
npm http GET https://registry.npmjs.org/bignumber.js/1.0.1
npm http GET https://registry.npmjs.org/require-all/0.0.3
npm http 200 https://registry.npmjs.org/require-all/0.0.3
npm http GET https://registry.npmjs.org/require-all/-/requi...
npm http 200 https://registry.npmjs.org/bignumber.js/1.0.1
npm http GET https://registry.npmjs.org/bignumber.js/-/bign...
npm http 200 https://registry.npmjs.org/require-all/-/requi...
npm http 200 https://registry.npmjs.org/bignumber.js/-/bign...
mysql@2.0.0-alpha7 node_modules/mysql
!"" require-all@0.0.3
#"" bignumber.js@1.0.1
Monday, March 11, 13
54. NPM LIST
$ npm ls
/srv/node
#"$ mysql@2.0.0-alpha7
!"" bignumber.js@1.0.1
#"" require-all@0.0.3
Monday, March 11, 13
55. NPM UPDATE
$ npm up
npm http GET https://registry.npmjs.org/mysql
npm http 304 https://registry.npmjs.org/mysql
npm http GET https://registry.npmjs.org/require-all/0.0.3
npm http GET https://registry.npmjs.org/bignumber.js/1.0.1
npm http 304 https://registry.npmjs.org/bignumber.js/1.0.1
npm http 304 https://registry.npmjs.org/require-all/0.0.3
Monday, March 11, 13
56. NPM REMOVE
$ npm rm mysql
$ npm ls
/srv/node
#"" (empty)
Monday, March 11, 13
64. EVENTEMITTER
messageBus.js
var EventEmitter = require('events').EventEmitter,
util = require('util');
var MessageBus = function () {};
util.inherits(MessageBus, EventEmitter);
exports.MessageBus = MessageBus;
Monday, March 11, 13
65. EVENTEMITTER
events.js
var MessageBus = require('./messageBus.js').MessageBus;
var mb = new MessageBus();
mb.on('message', function (data) {
console.log('Received new message: ' + data)
});
mb.emit('message', 'Hello World');
Monday, March 11, 13
66. EVENTEMITTER
$ node events.js
Received new message: Hello World
Monday, March 11, 13
67. EVENTS
• Wo kommen Events zum Einsatz?
• child_process, cluster, dgram, domain, fs, http, net, readline,
repl, stream, tls
Monday, March 11, 13
93. APPEND FILE
$ cat input.txt
Hello World!
var fs = require('fs'),
data = process.argv[2] || 'Hello my World';
fs.appendFile('input.txt', data, function (err) {
if (err) {
console.error('Could not write into file');
return false;
}
console.log('Success!');
return true;
});
Monday, March 11, 13
94. APPEND FILE
$ cat input.txt
Hello World!
var fs = require('fs'),
data = process.argv[2] || 'Hello my World';
fs.appendFile('input.txt', data, function (err) {
if (err) {
console.error('Could not write into file');
return false;
}
console.log('Success!');
return true;
});
$ node appendFile.js 'Hallo München!'
Success!
$ cat input.txt
Hello World!Hallo München!
Monday, March 11, 13
95. WATCH FILE
var fs = require('fs');
fs.watch('input.txt', function (e) {
if (e === 'change') {
console.log('File changed');
} else if (e === 'rename') {
console.log('File renamed');
}
});
Monday, March 11, 13
96. WATCH FILE
var fs = require('fs');
fs.watch('input.txt', function (e) {
if (e === 'change') {
console.log('File changed');
} else if (e === 'rename') {
console.log('File renamed');
}
});
$ node watchFile.js
Monday, March 11, 13
97. WATCH FILE
var fs = require('fs');
fs.watch('input.txt', function (e) {
if (e === 'change') {
console.log('File changed');
} else if (e === 'rename') {
console.log('File renamed');
}
});
$ node watchFile.js
$ echo 'Hello World!' > input.txt
Monday, March 11, 13
98. WATCH FILE
var fs = require('fs');
fs.watch('input.txt', function (e) {
if (e === 'change') {
console.log('File changed');
} else if (e === 'rename') {
console.log('File renamed');
}
});
$ node watchFile.js
$ echo 'Hello World!' > input.txt
$ node watchFile.js
File changed
Monday, March 11, 13
110. CHILD_PROCESS
• spawn - Kommandoausführung
• exec - Kommandoausführung in Puffer
• execFile - Dateiausführung in Puffer
• fork - Node Prozess
Monday, March 11, 13
111. ETWAS RECHENINTENSIVES
cp1.js
module.exports = function () {
var i, n = 1, results = 1;
primeLoop: while (results < 300000) {
n += 1;
for (i = 2; i <= Math.sqrt(n); i += 1) {
if (n % i === 0) {
continue primeLoop;
}
}
results += 1;
}
return n;
};
Monday, March 11, 13
112. potenziell
ETWAS BLOCKIERENDES
cp2.js
var http = require('http');
http.createFakeServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Monday, March 11, 13
113. ETWAS BLOCKIERENDES
cp3.js
var http = require('http'),
prime = require('./cp1.js');
http.createServer(function (req, res) {
console.time('Request answered in');
console.log('incoming Request');
var number = prime();
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
console.timeEnd('Request answered in');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Monday, March 11, 13
114. ETWAS BLOCKIERENDES
$ node cp3.js
Server running at http://127.0.0.1:1337/
incoming Request
Request answered in: 4713ms
incoming Request
Request answered in: 4703ms
Monday, March 11, 13
116. CHILD_PROCESS
cp4.js
var http = require('http');
http.createServer(function (req, res) {
console.time('Request answered in');
console.log('incoming Request');
require('child_process').fork('./primeHelper.js')
.on('message', function (data) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('The 300000st prime number is: ' + data.prime);
console.timeEnd('Request answered in');
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Monday, March 11, 13
117. CHILD_PROCESS
primeHelper.js
var prime = require('./cp1.js')();
process.send({'prime': prime});
Monday, March 11, 13
118. CHILD_PROCESS
$ node cp4.js
Server running at http://127.0.0.1:1337/
incoming Request
incoming Request
Request answered in: 4242ms
Request answered in: 4913ms
Monday, March 11, 13
119. CHILD_PROCESS
• Threadmodell von Node.js
• Möglichkeiten von child_process - fork, spawn, exec
• Kommunikation zwischen Eltern- und Kindprozess
Monday, March 11, 13
121. CLUSTER
• Loadbalancing über CPU
• Funktioniert mit allen Instanzen von “net.Server”
• ...auch mit http
Monday, March 11, 13
122. cluster.js
var cluster = require('cluster'),
http = require('http'),
workers = 2;
if (cluster.isMaster) {
for (var i = 0; i < workers; i++) {
cluster.fork();
}
} else {
console.log('Worker ' + cluster.worker.process.pid + ' started');
http.createServer(function(req, res) {
console.log('Worker ' + cluster.worker.process.pid + '
responds');
res.writeHead(200);
res.end("hello worldn");
}).listen(8000);
}
Monday, March 11, 13
123. clusterClient.js
var http = require('http');
for (var i = 0; i < 100; i++) {
http.get('http://localhost:8000', function (res) {
console.log(res);
});
}
Monday, March 11, 13
127. UNITTESTS
• Absicherung von Applikationen
• Tests auf Funktionsebene
• Node.js testet eigene Module ebenfalls
• Assert-Modul
• node-v0.8.22/test/simple
Monday, March 11, 13
129. ASSERTION TESTING
• var assert = require(‘assert’)
• Assertion-Methoden
• Sehr wenig Rückmeldung
• Nur ein Failure
Monday, March 11, 13
130. ASSERTION TESTING
fail Wirft einen
AssertionError
ok(value, [message]) Pass, wenn der Wert
true ist
equal(actual, expected, [message]) Vergleich mit ==
deepEqual(actual, expected, [message]) Vergleich über
Strukturen
strictEqual(actual, expected, [message]) Vergleich mit ===
throws(block, [error], [message]) Pass, wenn eine
Exception geworfen
wird
NOT! - notEqual(...)
Monday, March 11, 13
131. ASSERTION TESTING
assert.js
var assert = require('assert'),
actual = 'Hello World',
expected = 'Hello World';
assert.equal(actual, expected, 'Strings are not Equal');
assert.notEqual(actual, expected, 'Strings are Equal');
assert.fail('FAIL!', 'PASS!', 'This fails!');
Monday, March 11, 13
132. ASSERTION TESTING
$ node assert.js
assert.js:102
throw new assert.AssertionError({
^
AssertionError: Strings are Equal
at Object.<anonymous> (/tmp/node/assert.js:7:8)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:
244:9)
Monday, March 11, 13
138. PROMISES
• Ergebnis eines asynchronen Funktionsaufrufs
• Rückgabewert oder Exception
• Promise statt Blocking
• CommonJS Proposal
• Bis 0.2 Bestandteil von Node
Monday, March 11, 13
139. PYRAMID OF DOOM
step1(function (value1) {
step2(value1, function (value2) {
step3(value2, function (value3) {
step3(value3, function (value4) {
// do something
});
});
});
});
Monday, March 11, 13
140. PROMISES
Q.fcall(step1)
.then(step2)
.then(step3)
.then(step4)
.then(function (value4) {
// do something with value 4
}, function (error) {
// Handle any error from step1 through step4
})
.end();
Monday, March 11, 13
148. KONTAKT
Sebastian Springer
sebastian.springer@mayflower.de
Mayflower GmbH
Mannhardtstr. 6
80538 München
Deutschland
@basti_springer
https://github.com/sspringer82
Monday, March 11, 13