Loading...

Node introduction

Plan for today

The goal in this lesson is to cover the basics of Node. We will learn how to install node, learn about JavaScript and how to run it using node, and we will cover the built in modules that comes when installing Node. The aim of this tutorial is to be a good starting point for your exploration of NodeJs

What is NodeJs

NodeJs is a runtime for running JavaScript applications. It's built with the open source v8 javascript engine which is the interperter that executes our js code. JavaScript is well known for the ease of use of asynchronous events and that is one of the high points of using Node. This means that NodeJs will in most cases avoid in blocking the main thread and will depend highly on async events. A common example of such behaviour is when performing a database query, in most web server technologies, we will perform a query for the database, wait for the result to comeback and then continue. When using node we will send our database query and connect an event to run when the results come back. The async events are easily subscribed without worrying about openning a thread or locking resources, in fact most of the node javascript code we will run will be on the main thread, and we will rarely use threads (although is possible with node). When we have an async event like our database returning the data, node will subscribe the event to something called the Event Loop, when node is idle and not currently running anything, it will check if something from the event loop needs to be run and will run it.

What is JavaScript

JavaScript is a single threaded - there is one thread running our js code.
Dynamic language - no compilation, no variable type.
Interperted language - there is no compilation, so the interperter of the code (rather it comes in our browser or in node) will go over our script line by line and figure out what to do.
Object Oriented programming language
JavaScript api is decided by ECMAScript and is opensource.
Every year there is an update that ECMAScript is publishing and every JS runtime makes the update at his own pace.

Event Loop

The event loop is what allows Node to perform non blocking operations. We mentioned earlier that JavaScript is a single threaded language, which is not a 100% accurate thing to say. One of the strong points of Javascript is the fact that is lets us program in an environment where we have to focus on a single thread but on the background node will use multithreading. Part of the nodejs code is written in C++ and in C++ we can manage threads, and in fact nodejs by default will manage a thread pool of 4 threads. Moreover whenever possible the C++ code will transfer work to the kernel where more multiple thread work will be done there. So the event loop allows us to use a single thread language like JS in a multithread environment. The event loop job is to orchestra the async job, some will be transfered to the c++ part where it might work on one of the 4 thread in the pool, or perhaps the c++ might transfer it to the kernel. When the job is done it will signal back the event loop and the event loop (running on the main js thread) will run the callbacks returned in a queue.

Installing NodeJs

NodeJs can be easily installed by openning the following url: NodeJS Download the latest package and follow the installation guide. To verify the installation: In the terminal type:

        
            > node -v
        
    

This should show you the current running version of node, and if it does it means the installation is successfull.

Multiple NodeJs environments

Lets describe a problem: Say you want to work on a node project and your current node version is 6.5. you commit your code and push to a remote repository where your team mate running node v10.0 is working on the project and push some code as well. You download that code only to find our that it breaks the running of the application. Its important for all team members to run the same node version. To deal with this problem you can use nvm Install it with the following command:

        
            > curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
        
    

if the installation went good you should be able to run:

        
            > nvm -v
        
    

Now to install and use a node version you can simply run:

        
            > nvm use <node-version>
        
    

but instead of communicating this to all the team members that they should use this version, and also trust them to do the use command before working, there is a simpler solution. You can add in the root directory of the project, and of course commit this file to the repository, a file called .nvmrc. This file will specify the node version to use. When this file is located, running the command:

        
            > nvm use
        
    

Will download (if needed the environment) install (if needed) and use the node version specified in this file. Instead of remembering to run this command every time you open the project, you can add a bash gist to your ~/.zshrc That will automatically run the nvm use command when there is a .nvmrc file in the current directory. Modify the ~/.zshrc file and add the following to the bottom.

        
            autoload -U add-zsh-hook
load-nvmrc() {
  local node_version="$(nvm version)"
  local nvmrc_path="$(nvm_find_nvmrc)"

  if [ -n "$nvmrc_path" ]; then
    local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")

    if [ "$nvmrc_node_version" = "N/A" ]; then
      nvm install
    elif [ "$nvmrc_node_version" != "$node_version" ]; then
      nvm use
    fi
  elif [ "$node_version" != "$(nvm version default)" ]; then
    echo "Reverting to nvm default version"
    nvm use default
  fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc
        
    

We won't go over exactly what the script does, but the result of this is when you open a new terminal automatically you will use the current version of node for the project.

Node cli

After we installed node lets go over a few commands exposed to use in the terminal.

        
            > node
        
    

This will open a node interperter where you can write js command which will be evaluated. You can press the tab key while the interperter is open for command complete.

        
            > node <filename>
                
    

This will run the file

        
            > node
            > .editor
        
    

This will go to editor mode where we can write multi line javascript code. run it with Ctrl + D

        
            > node
            > .save <filename>
        
    

This will save the current session to a filename.

        
            > node <filename>
        
    

This will run the script.

Hello World

Lets start experimenting with node and the first program we will create is an hello world program. Open the node interperter:

        
            node
        
    

pressing tab twice you can see the global objects and functions you have. One of them is console which is also in charge of log message on the screen. The method console.log can print message on the screen. Type the following:

        
            console.log('hello world');
            console.log("hello world");
            console.log(`hello world ${1 + 1}`);
        
    

we are calling the console.log function with a string argument. Notice the different kind of supported string you can do in JavaScript. You can save the program by typing in the interperter

        
            > .save hello-world.js
        
    
Summary

This lesson covered a really basic introduction about node. We explained what is node what is the event loop showed best practices when working with team and different node versions. explained also about the node repl. And showed a basic hello world application. Our next node lesson we will cover modules.