Node introduction

Course Home | Programming

Before we start looking at code it’s worth learning a bit of history around the relationship of JavaScript and Node. If you’ve ever accessed a web page then you have undoubtedly used JavaScript. Whenever a new element is created on a web page, the style of some text changes suddenly or new values are injected into a table it’s likely that JavaScript was used to create that behaviour.

Over the past 20+ years JavaScript has become more and more advanced, with companies now developing whole applications that run within the browser (as in they don’t have a backend at all). This has been in part due to the active development carried out by organisations such as Microsoft, Mozilla and Google, whose V8 JavaScript engine that lives in Chrome was the basis of Node.JS.

Node.JS was created in 2009 and is a JavaScript based language that comes with a few extra bells and whistles to create things such as web services and automated regression checking tools. It’s use has exploded over the years with Developers and Testers alike using it in all sorts of ways to solve problems. For this series we will be looking specifically at Node.JS and it’s syntax for different programming techniques.

Running JavaScript files in Node.JS

To run JavaScript with NodeJS. You need to ensure that you have NodeJS installed, which you can do here. Once installed create a file named myFirstJavascript.js and add in the following code:

console.log("Hello World!");

Save the file and then open a command line or terminal window in your operating system and navigate to the directory that contains your file and run:

node myFirstJavascript.js

You should see the words Hello World! appear. Congratulations, you’ve just run your first NodeJS script!

Node.JS architecture

Unlike other languages like Java, Ruby or C#, Node works a little differently. Node operates on a single thread, executing methods asynchronously. This means the syntax for Node differs from other languages. To understand this in more depth let’s compare an example of Java vs Node.JS.

First up, let’s say we have this code in Java:

// Print first message
System.out.println("Event 1");

// Wait five seconds

// Print second message
System.out.println("Event 2");

This will print

Event 1
Event 2

This is because Java works from top to bottom executing each line, waiting for the line to complete (such as waiting for 5 seconds) before moving onto the next line.

Now let’s take a look at something similar in Node.JS:

// Wait five seconds and then print the first message
    console.log("Event 1")
  }, 5000);

// Print second message
console.log("Event 2");

This will print:

Event 2
Event 1

Newcomers to Node will naturally by thrown off by the fact that ‘Event 2’ comes before ‘Event 1’ but there is a logic to it. Unlike Java (and other similar languages) Node doesn’t wait for each line to finish executing before starting the next one. Instead Node roughly sends each function to be executed in it’s own context or thread.

So that means setTimeout is run in it’s own thread and then Node moves straight to console.log("Event 2") ands runs that in it’s own thread. This means that both functions will be running at the same time. Once every thread is completed the Node observes there is nothing left to do and quits.

Working with Callbacks

So in Node it’s not as simple as arranging a series of functions to run line after line and expect them to run. This might seem daft, but it does mean Node is designed to be a highly performant language that can run multiple threads at once.

However, there are times we do want functions to run after one another, as we can see with the setTimeout function that waits 5 seconds and then outputs ‘Event 1’. This can be achieved with the use of callbacks. Callbacks are a tricky thing to understand, but they are essential tool in Node so you should take time to really understand how they work.

One of the reasons Node is popular is because it’s a dynamic language. This means that you can store anything as a variable ranging from numbers and strings to functions.

Let’s take another look at setTimeout again from the previous example:

    console.log("Event 1")
  }, 5000);

setTimeout takes two parameters. The first is a function that we want to run after the timer has expired and the second is the time in milliseconds to wait. If we were to look at the guts of the setTimeout function it might look something like:

function setTimeout(myCustomFunction, timeToWait){
  wait(timeToWait); // Or similar

Notice how the myCustomFunction parameter is called as a function after the wait. This is because whoever created the setTimeout function expects myCustomFunction to be a function that can then be executed once everything else has been carried out with the original setTimeout function.

The declaring and running of myCustomFunction is known as a callback as it’s calls back the function it was given at the start of the run of the function.

Wrapping up

This can all seem a little confusing at first, but it’s essential to understand before starting anything advanced with Node. Remember if you find yourself asking ‘why is X running before Y’ then it is probably due to an issue with callbacks.

Next Lesson ➔

Mark Winteringham's photo

Mark Winteringham


Mark Winteringham is a tester, toolsmith and the Ministry of Testing DojoBoss with over 10 years experience providing testing expertise on award-winning projects across a wide range of technology sectors including BBC, Barclays, UK Government and Thomson Reuters. He is an advocate for modern risk-based testing practices and trains teams in Automation in Testing, Behaviour Driven Development and Exploratory testing techniques. He is also the co-founder of Software Testing Clinic a community raising awareness of careers in testing and improving testing education. You can find him on Twitter @2bittester.