 Thank you very much for your time. All right, everybody. Welcome to the last talk of the day, excluding lightning talks. And welcome, Lukas. So thanks for coming. It's a little bit late. And you are, I believe that you would like to be in a pub at this point. So I will make it quick, hopefully. I would like to welcome you on a session about Node.js. It will be a gentle introduction, which is slightly biased to Java devs. But I promise, even if you don't know anything about Java, you will get something for it. My name is Lukashvich, and I have, like, three years, three years long experience with Node.js. But I am writing JavaScript for, like, 15 years already. So I may tell you a lot of interesting things from Javaland. Today, first, I will tell you what Node.js is about and what it is not about. And we will dive into a few things that you will definitely face when you will first encounter Node.js programming. And those things are even loop and asynchronous workflows. Then we will a little bit dive into parallelization of Node.js programs. And we will also look into how to make our programs modular. I will compare a bit of Java, some simple constructs that Java people or Java code usually are looking for in JavaScript and Node.js specifically. We will look a bit into translation, but really fast. 40 minutes is not that enough. And I will also mention a few tools that you will find useful when programming in this land. But first, let's start what's actually Node.js about. First, let me declare Node.js is not any language. It uses just ECMAScript as we know it from browsers. And it's also not any framework. You won't find any framework stuff in Node.js. Basically, base Node.js APIs are that low-level that we can really treat it as the framework. But it's a platform. It's a runtime and a platform with a lot of extensions that you can leverage. If we want to compare the concepts, we know the language of Java. Of course, Java language, the language of JavaScript of Node.js is JavaScript. We run Java on a Java virtual machine, while Node.js is powered by V8, which is the Google Scrum virtual machine. Then we have Java development kit that we can compare it to Node.js standard modules. Basically, that's it. If you would like to start with Node.js, just go to Node.js.org and download the latest table 5.5 version. Or if you want to run it in production, let's go to long-term support, which is, I believe, two years long, which is still pretty good. Then Node.js is... First encounter with Node.js will be one going to the shell and using tools like Node. I'm not personally downloading the distribution of Node.js directly. I'm using the Node version manager, which I really encourage you to use, because if you are switching between version a lot, then it will come very handy. So I may switch or install versions very simply. So basic tools are Node, which is basically the interpreter of dynamic language. So hello. Good. And the second tool, which you will definitely use, is Node package manager, which can be compared to Maven. That's basically the package manager, the dependency manager, which comes with some standard workflows. So with NPM, we can initialize new project. I will just go with defaults. Now we have package JSON. Now if we want to install something like probably most used module, which is Express, we will just save it to package JSON. And now if we look to the package JSON, you will see that we got one new dependency. It's really that simple and fast. So the Node application will basically look for the main script, which is not here, so we would have to create it. And we could run it, but it will, of course, do nothing. So yeah, basic workflow. The most basic APIs we can use in Node, you can see that, I hope you can see. If you will list the Node API documentation, you will see that all of them are really low level. Nothing that you could just use. For example, HTTP module is something we could simply compare to Java cellulets. However, the real power of Node.js doesn't come from the runtime itself. It comes from the number of packages, the plethora of packages. The NPM repository is actually the package repository, which has most packages in comparison to any other language platform, runtime, whatever. So on NPMjs.com, you can find new packages for, for example, let's say we want to use Promises, which I will show later. I can find some popular module here, like Express or Browserify, that's cool. So that's probably the entry point for all the reusable modules. But you may ask me why I should leave when considering you are Java developer, why you should leave your safe place, the Java land, its type safe, what can actually JavaScript give me? If I'm considering myself, the best thing on JavaScript is that it's everywhere. It started with browsers, and I may tell you that you can imagine 15 years ago the JavaScript era really sucked, but nowadays it is that powerful that it can simply power the mobile applications and very complex applications like Gmail on browsers, and of course we have it already on server. And that actually enabled JavaScript developers the perfect match that they can develop all the client applications, and they are writing in the same language. That's something I was looking for in Java for years, and I couldn't find it even though I was using GWT and so on. It didn't feel right, but writing in the same language that's just so powerful. And also a new superstar at that point where I was born, it's called Fullstack Developer. It's the guy who doesn't care whether he writes the client or server. There is no more distinction. You are just writing both and you are proactive in both ways. But the client and server applications is not all. Of course JavaScript is in IoT land, and for Java people it's on JVM as well. You can run it as Vertex, as Nodin. You can use Nashorn, Dyn.js. There are so many projects built around running JavaScript on JVM or even Node on NVM. One note to that, even though we have Node on JVM, you can still run all modules that you will find in MPM repository on Node on JVM because there are the native bindings that uses C++ level APIs. That's why that will never be that simple, but still you can use just one language. But what really makes Node.js so different that it may be that hard to learn for a lot of people. The single most interesting and important thing to learn when you are going to JavaScript is actually learning about Event Loop. Event Loop is basically single thread. Node.js, every time Node.js runs just in single thread, which is perfect because you don't have to address any synchronization or anything like that. If you want to communicate with other programs, you just use message passing. So you run in one thread, but it could scale when you run in one thread. The basic idea of Node.js is that the most time-consuming things are actually I.O. It's from receiving requests to sending requests to reading file system. Every I.O. is so time-consuming that every such operation Node.js wants to delegate to thread pool, which will basically operate all the time-consuming operations. This single thread is just for our business logic. It was proven that our business logic is usually that simple, just some ifs. It's so simple that we can serve so many requests just in one single thread. What happens when we have, for example, requests? We want to request something on some REST API. At that point in a program, we will basically fire a request to the thread pool, and the state of the scopes will be remembered. Now it's on non-blocking lip UV to handle that request. Once it's processed, it will basically come to the event queue, which the single thread uses as a source for new logic. It's basically every time spinning thread, which just fires even to the thread pool and then waits for the result to process them. So it's on-blocking, it's highly asynchronous, so it's pretty performant. If you still can't get around it, I hope it's clear from the previous image. But let's just remember that it's like comparison of your favorite fast food when if you go to the Drive 2, you will just go here and order, and you don't wait for the response. You go here, you will pay, and once you pay, you go to the last window and you get your result. But in traditional Java multithreading, it's like this, you are standing in the queue, and you are waiting for the thread to be cleaned up, to clean up the last work in order to process some new orders. But it also comes with some trade-off that we also have to have language constructs that enables us to write programs effectively. And I think a lot of confusion and a lot of hatred about JavaScript or Node.js come from the concept which is callbacks or sometimes airbags. Sometimes Java Cloud just tweets about callback, and I will show you why. So the basic idea is that we are using callbacks. If we wanted to get something from a request, then we just describe what we want, and now we pass the callback. That callback always by convention starts with error object, our error variable. So if the response will be error-nose, then this error will be actually not null. So what we can do if this function has a contract that the callback is passed as well, so we just propagate the callback more, and otherwise we will parse the body. It's pretty obvious. But let's look at not that simple application. I have prepared here an application which is Express. Express is like an industry standard for writing Node.js REST routes, and there is just a simple, possible, probably, API which just returns empty JSON. Here you can see that we have one route called data, and it's get, and if we want to change the pose, we will just do this. It's that simple, and then we use some middleware, and then that middleware is actually error handler. We can identify that by this first parameter error. So if some error happens here, we can propagate it to the error handler here, and it will just use the default error handler where if there is some message, it will return it. If not, it will create one, and at the end, we will listen on some port. It's still simple, so let's look for a little bit harder example. We have the same endpoint, but we want to do more here. We want to request data from two endpoints and then merge the result and provide it to the user, and we want to also leverage cache if the requests were successful. So now we start request processing here, request, response, and next handler. We use Redis for caching, so do we have anything in Redis cache? If there are cache data, we will just send them to the user. If not, we will create an object that we will want to fill. So we will fire two requests, and one is to our Java old backend application, and the other one is to the third-party API. We want to merge those results and send them, for example, to our mobile devices. So again, there are callbacks, because these two are asynchronous operations. If there is error, we will handle it. If not, we will fill in the data, the parse data. We also want to get rid of some confidential information from the response of our Java backend, and then at the end, we have to try to respond because we don't know which one of these will respond first, so we are basically waiting for both of them, and once both of them are filled, we will respond, and then try to cache the information or the response we had got. Let me just quickly show you how we can debug this, and I have to switch from presentation view. Actually, just to run it, I will run it. It's listening, so I will show you that I can not watch, but I can retrieve some data. So in order to debug this, I will add there some breakpoints, and to understand asynchronicity, we will use these breakpoints. So we are listening again, let's find a request, and we hit the first, what? Okay, sure. We hit the second breakpoint, and now we actually got a response from the application, and we got a response from the second endpoint, and now they try to respond, and that's it. We got a response. But that's not that powerful. In order to handle the asynchronicity much better, something which is language construct in ECMAScript 6 called Promises was invented, and Promises is basically a continuous passing flow pattern where once the first promise resolves, the second promise which is defined or registered by a then handler will be called, can do something with data, and then will be called once it is handled asynchronously, the first then, and then the second then will be handled, and if anywhere in this flow something happens, the last error handler will be called. So we can rather write something like this. We all have function retrieved third-party data, and when we know that this API request is also returning promise, then we can say that let's request it, then parse it. You can see that JavaScript is a functional language. We are treating functions like JSON parse as a first class citizen, and so at the end, our programs finally look a little bit more readable than just with callbacks. So typically what I may do in my API is logging start, which will probably be debug log, then retrieve the data, set it into the cache, then log the request and handle error very readable. Let me put here the second example, which is using Promises. I will make it bigger again. So now you can see it should be more readable. So let's take the handler function. The handler function will call getData, which is promise. The promise again uses some promise getCachedValue, then if there is someCachedValue, I will directly return. So here we are returning value, but if we don't have it, we will return promise instead, and if we are returning promise, then another handler will wait until we have the result. So you can see that we are returning either the value or the promise. And after the data are retrieved, we save them to the cache. So we can reason about this pretty well, right? This is pretty nicely written workflow of our API. If we are using it on a high level, we just say, let's get me data, and if there are data, respond them. You can see that we are using another ECMAScript6 feature, which is an error function. We can compare it to Lambda's in Java, and if there is error, we will just pass the next. The next has the API that we just passed the error, so we can just pass next, and it will handle errors automatically. Another promise-based API is promise-all, where we can retrieve all where we say, let's wait for both of these functions to wait, and then process them. The processing goes in the way that here is another ECMAScript6 feature, which is an array reconstruction. We know that we will get an array from this promise-all because we have two results. We can automatically assign them to the array variables, and here is another feature, which is simplified object construction. This one will basically take those two parameters and store them under the object fields, which are called backend data and third-party data. Just if we are using some APIs that aren't written in a promised way, for example, RadisCache is an exposed that way, we can use libraries like Bluebird, which allows us to call promise-promissify all on the object, and it will basically take all the methods defined or functions defined on that object and wrap them in a function name async pattern. You can see getAsync and setAsync, and it basically returns promises. Just so that you would believe me, let's run it again. I will run it with Nodemon. Nodemon is a nice tool in order to not spend time reloading the application all the time. You can run Nodemon, and the address is still in use. Why it is still in use? Because I still run it here. View, exit, and kill this. Good. Now you can see if I do some change here. For example, I will leave it to listen of 50-50. It's constantly reloading. I'm passing one parameter here. It's a harmonic destructing, which is the flag which provides me with some features that are still in there defined in a spec, but the specs are usually finalized yet, but still they aren't stable in Chrome in V8, so that's why I can enable them with harmonic flag. For example, the feature I have shown you before. If it is still... Sorry. You can see a little bit of analogy between the Java, util, concurrent, future, and promises, if you want. However, if it's still not enough for you to think about or reason about asynchronous logic, then you should wait for ECMAScript 7, which will basically allow us to use async evade API, where it is compatible with promises, so this async function is basically promise, or we can use it as a promise. We could call the respond den, and here I am using evade. Evade will basically mean that I am waiting for some blocking operation, or I will basically suspend the computation, and the nice consequence is that in such a written snippet, I can actually use striketch finally as I would in any other logic. Just let me go quickly to parallelization. So parallelization is as simple as this. You will just run it so many times with parameters like port, or you can use docker, of course. Nothing surprising, but if you want to go more low-level, you can actually spawn more processes, but that's still not what we would like to use in the server-side applications, so that's why Node has a cluster module. Cluster module is something which... it's a module which allows you to fork the process, for example, as many times as you have computer units, and then it will basically rerun our snippet. So we have a flag here, which is called isMaster and isWorker, and we basically know in where we currently run. The master process, or the process itself, the cluster module basically listens on that port, and it uses around Robin to go around all the workers that we have spawned. So if we would run this on my machine, we would see that we have four processes, and all of them can handle 80, 81 port. It's not a very nice code to read, so we have invented... we have written a small library for Henry Custer that helps us to write microservices just in a way where we use Express API, and it's much more easier to read. Modularity. So you could probably already notice how Node.js modules are written. The basic API requires some module name, either the global module here, or the one installed in Node.modules directory, or you can use relative path to module, and this is one of the APIs that is blocking, because that require has to block until the module is created. So if we have this, we require some modules, and then we want to expose some module functionality so we can depend on it. We can use module exports and pass the objects, which will be exposed to the outside. Okay, so for packaging, we use NPM to install anything. We use NVM for switching versions, but let me talk a bit about versioning. Versioning may be tricky, however, pretty nicely solved. If we go to package JSON, we will see that our dependencies were installed with some of these patterns. We have carried and version. What does it mean? So basically Node uses semantic versioning, so anything which starts with zero is not stable, and you should not depend on it. I can tell you that at this point most of the standard modules that I use are in stable mode. They are one point anything or more, which is surprising. When I was installing some project last time, I have noticed that all of the dependencies are one point something, and I was pretty confused. It never happened before. However, in Node.js, in package JSON, we can specify ranges. These ranges are basically pretty self-describing. However, if you still do, you basically say that you want this version and any other minor version, like non-API breaking version here. If you still do, that's the same. You just say that you want one point anything. The correct doesn't work the same way with zero version, non-stable versions. If you specify it this way, then it means that because the API may be unstable, it can change in whatever version Outor wants. So then something will basically stay the same. Node won't try to install it. Just quickly, when you are installing the dependencies in Node, you have two ways how to unlock the dependencies. You can either check Node modules to get up, to get the repository, which is not nice to our source. You can use NPM shrink web. NPM shrink web is basically the NPM command which will write a nice JSON full of information, and it will basically describe everything you have installed with NPM into the Node modules folder. Let me try it, for example, here. NPM shrink web. On my test, I have created previously, and it will do this. Now, if we have this descriptor in this folder, it will basically use it if you write... Oh, sorry, I'm using another display. Again, test NPM shrink web, and look at NPM shrink web JSON. It will now use the NPM shrink web if I write NPM install instead of my package JSON. Right? Good. So, for Javaists... So, for Javaists, we have classes in ECMAScript 6. I wouldn't use them as much. I would just... I wouldn't use them that much as you do in Java. Use other patterns. I will show you some books where if you are really interested in JavaScript, then let's... Don't use classes that much. People in open source community will love you. Dependency injection is possible. For example, in alternative asynchronous module loading or the definition strategy, you basically can describe the name of the modules we use, and then they will be passed into the function. Or similarly, in Angular, we can... Angular just parses the parameters of the function in order to get the names of the variables defined, and it will use the name to inject my dependency. So, something which starts with $ is the system Angular dependency usually, while this MyLogger is something I have defined. Reflection is much simpler. Reflection is just about iteration over the properties in the object. While Proxies, Proxies were added in ECMAC script 6, but not much implementations implement them at this point, but they are pretty comparable to what we have in Java. What about Java EE? If you compare to Java EE, I may tell that from my experience, it's much faster to write express applications than Java EE, but obviously, there are analogous APIs we can leverage. Also, configuration is usually driven programmatically, and it's much better than bloated XMLs, right? Or, for example, handling asynchronous calls is also pretty easy in Java EE latest versions. However, I still like promises more. If you still are not happy about how JavaScripts look like, you can do a little bit more Python way, which I don't admire anyhow, but you can do that, obviously. You just need to do some translation before you run your program. I'm much more in favor in getting a little bit type-safe using type-safe interfaces like with TypeScript. So, just at the end, let me talk you what we have already seen. Node.js applications are usually written or that they start that fast, that we can use something like NodeMonitor, which will restart our application every time the source is changed. So, it starts in seconds. So, it means it is really, really fast for redeployment, say. You can use whatever IDE. I prefer WebStorm. It has really nice code completion. It's quite clever. Sometimes, if you call your Mephotlite get, it can't reason about it, but if you are clever about it and use meaningful Mephot names, then you are safe. But you can use Vim, Notepad. You can use even Emacs or something like that. Debuggers. There are Chrome DevTools, especially optimized for Node.js, which you can use familiar browser debugging things. But last thing I would say, because I'm out of time, be sure to use something like ESLint or JSHint or anything like that because JavaScript is sometimes tricky, so it is better to use some static code analysis. And it is always good to use test runners. For example, the one I have here is DeadGood that it reruns every time I change the application. So I will just show you. If I run Watch, right, I would have to change it, but if I run Test, it will basically run Test in a second. So let me just recommend last thing. Some books. Some of them are new. Some of them are older. But be sure to read about JavaScript before you start to use it. It can be applied to anything, but you will be so happy when you find yourself writing pretty nice code and the code which you can reason about. So yeah, that's it. I hope that it was a nice interaction for you and I certainly welcome you to Node.js community now. I want to see more GitHub modules in NPM registered each day. Okay. Thank you, Lukash. Unfortunately, we don't have time for questions. Unfortunately, we don't have time for questions for the whole room, but you can always speak to Lukash. Just a reminder, Lightning Talks will be in the D section. Thanks for coming today.