Node.js runs as a single-threaded process that acts upon callbacks and never blocks on the main thread, making it high-performing for web applications. A callback is basically a function that is passed to another function so that it can be called once that function is done. We will look into this in a later topic. This is known as the single-threaded event loop model. Other web technologies mainly follow the multithreaded request-response architecture.
- Creating REST APIs: We are going to look into this more in subsequent chapters
- Creating real-time services: Because of Node's asynchronous event-driven programming, it is well-suited to reactive real-time services
- Building microservices: Since Node.js has a very lean core, it is best suited to building microservices, since you will only add dependencies that you actually need for the microservices, as opposed to the glut that comes with other frameworks
- Tooling: For example, DevOps automations, and so on
Before You Begin
Learn how to write a basic Node.js file and run it.
You are writing a very basic mathematical library with handy mathematical functions.
Steps for Completion
- Create your project directory (folder), where all the code for this and other chapters will be kept. You can call it
beginning-nodejsfor brevity. Inside this directory, create another directory named
lesson-1, and inside that, create another directory called
activity-a. All this can be done using the following command:
mkdir -p beginning-nodejs/lesson-1/activity-a
activity-a, create a file using
- Inside this file, create the following functions:
add: This takes any two numbers and returns the sum of both, for example,
add, takes any number of numbers and returns their sum, for example,
sum(10, 5, 6)returns
- After these functions, write the following code to act as tests for your code:
console.log(add(10, 6)); // 16 console.log(sum(10, 5, 6)); // 21
- Now, on the Terminal, change directory to
lesson-1. That's where we will be running most of our code from for the whole chapter.
- To run the code, run the following command:
21 values should be printed out on the Terminal.
Even though you can configure the IDE so that Node.js code be run at the click of a button, it's strongly recommend that you run the code from the Terminal to appreciate how Node.js actually works.
For uniformity, if you are using a Windows machine, then run your commands from the Git Bash Terminal. For the reference solution, use the
math.js file at