Taking a hot shower after a tiring day is very relaxing. So I turn on the water heater and stand there waiting for water to be warm enough. Wait, ridiculous. Why am I waiting there. Can’t I do other things while heater does it’s job? If this is how I live my life then it’s pretty inefficient. I need to start living asynchronously. What do I mean? Lets say I’m chatting with my busy friend who replies really slow. If I sit idly doing nothing while waiting for his messages you would think I’m dumb and waste a lot of time doing absolutely nothing. A better thing to do is keep doing you job and every time you receive a message reply back quickly. This is of living asynchronously. Keeping this in mind lets talk about node.
What is Node.js?
Take example of a typical website. Generally there are three pillars to it.You application code that manipulates the data, database of the application and the environment in which your code resides. When a request for content hits your application, your code will fire a query on database. Now if your database if slow for some reason,your code waits there wasting CPU cycles. Why should your app wait for database to finish its operations instead of serving other requests. When database is ready to provide data it should notify your code, hey I’m ready with the data. Node does this.
Following code is example of blocking code
result = query(‘select * from mytable’);
And this is the asynchronous form.
query('select * from mytable',query_finished);//next line of code runs
query_finished function is listening for that event and logging result.
Multi-threaded Vs Single-threaded
If you wanna serve a lot of requests at a time then why not do multi-threading? Servers like Apache use multi-threading. That means it spawns a new thread for every new client. Each thread requires certain amount of RAM. Lets do some Math. Suppose your server machine has 2GB RAM and this RAM is shared between your database server,your code and other processes running on your server machine. Now consider high traffic situation. A lot of threads are created.They eat up considerable part of RAM and after a limit your whole machine just slows down because it runs out of memory. Now imagine your application is data-intensive like an ecommerce store, there will be lot of database input-output or file input-output or both. That means a lot waiting. It can not handle a lot of requests if your machine has less resources. Hence not scalable. Node.js uses single threaded event-driven approach which makes it light weight on resources and efficient. I’ll elaborate on that when we discuss event loop.
I’m super excited to share these little adventures with you. We will begin with ‘Hello World’ program and then move towards building a fully functional web server. Hence we will need to pay attention to details like building a form parser, templating engine, HTTP headers.
- You have Node.js installed
- You won’t copy paste code snippets.