Starting with Basics: Why Use Node.js?
Before we go any further, before we start with our first core feature of Node.js, I want to just bring everyone on the same level, and discuss some of the basics of Node.js.
Let's start with why we use Node. So in software engineering, typically we build two types of systems. One type of system is input and output, and typically it's the most expensive, and then the other type of systems, they are CPU bound.
So you either consume a lot of CPU or you consume a lot of input and output, and input and output, they tend to be more widespread systems, especially in web development. So Node.js has this thing, it's called non-blocking I/O, or non-blocking input and output, which allows us to build non-blocking I/O systems.
This is Java code in which we put the entire thread, the entire process to sleep. So thread.sleep . So 1,000 milliseconds would be one second. So we're going to line number one, then line number two, which will output step one, step two. Then the entire thing would be idle, it will be waiting, and then you would see step three. So you cannot do anything while this Java process is waiting one second.
Contrast that with this Node.js code. So first we would see step one, then we would see step two. So the entire definition, the statement, console.log, step three would be skipped. It would be scheduled in the future and only after one second, it will be executed, but the key here is that we can have more code in this process. So step four, it would run. It would not wait for step three, because step three, it's inside of the call-back. It's executed asynchronously in the future. So event loop will take the definition inside of set time-out. That's your call-back. That call-back will stay...will say step three and step five, and scheduled in the future. And then it will continue to run the code. So we can do interesting things like running multiple code in parallel.