Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Created June 30, 2015 17:17
Show Gist options
  • Save jim-clark/3396aaccdbeb765b7ffc to your computer and use it in GitHub Desktop.
Save jim-clark/3396aaccdbeb765b7ffc to your computer and use it in GitHub Desktop.

Intro to Node.js

Learning Objectives
Understand What Node.js Is
Use Node.js to Execute JavaScript
Use Node.js as a Basic Web Server

Roadmap

  • What is Node.js
  • Node.js vs Rails
  • Installing Node.js
  • Using Node.js to Execute JS
  • Node.js Modules
  • Simple Node.js Web Server

What is Node.js?

Facts about Node.js

Node.js is an open source, cross-platform runtime environment that executes JavaScript, primarily on the server-side.

Created in 2009 by Ryan Dahl with Joyent, Inc.

It is a misconception that Node.js is written in JS when actually it is written primarily in C++. The confusion comes from the fact that it uses Google's V8 JavaScript Engine to compile JS programs into machine code.

Node.js is designed to be very lightweight with minimal built-in low-level libraries specializing in working with the filesystem and networking.

Although Node.js is itself lean and mean, it's functionality is heavily extended by open source libraries, much like gems are used to extend Ruby. These libraries are often called modules, or packages, and are managed by a package manager, npm. npm is automatically installed with Node.

One of the most common packages used to extend Node is the Express.js framework. Express.js turns Node into a powerful web server.

Node and Express account for the "N" and "M" in the MEAN Stack. AngularJS and MongoDB being the other two technologies in the stack.

In late 2014, io.js was created based upon a fork of Node.js due to internal conflict with the way Joyent had been governing the project. However, the love birds have since made up with an agreement to work together under the Node.js Foundation, a newly formed, neutral group.

Why all the excitement over Node.js?

First and foremost, performance!.

Node was designed as an event-driven, non-blocking, single-threaded system. This may seem like a lot of technical jargon, but it basically allows a Node server to support tens of thousands of concurrent connections! This performance advantage equates to businesses being able to serve more customers with fewer computer resources - cha-ching!

Another nicety of Node is that since it runs JavaScript programs server-side, its easier to share developers across both the front and back-end. More clearly, Node makes it easier to become a productive, full-stack developer!

Businesses Saving Money === Wide Adoption === Demand for Node Developers - any questions?

Rails vs Node.js

Why Choose Rails?

  • Quickest path to building app with full CRUD
  • Better at working with complex data relationships - ActiveRecord rocks!
  • When full page refreshes aren't an issue
  • Easier to program because synchronous is easier than async programming

Why Choose Node?

  • JavaScript everywhere!
  • When performance matters
  • Handle more users with less computer resources (saves money)
  • Designed with more modern realtime, mobile and Single Page Applications in mind

Installing Node.js

To check if we already have Node installed, type node -v in terminal. You will see the Node version if it's installed, otherwise lets install it.

You can install from the Node.js website, or better yet, use Homebrew like this:

? brew install node

This will install both Node.js and npm, an important package manager for Node. One of the advantages of using Homebrew is that you can update your versions easily like this:

? brew upgrade node

Using Node.js to Execute JS

Node.js is a runtime environment for executing JavaScript. However, because we are not executing JS in a browser, there are no window or document objects.

Interactive Node

If you simply type node in terminal, you will launch Node's REPL (Read-Eval-Print-Loop) interactive utility. Think of REPL as Node's version of Ruby's IRB. Let's test it:

? node
> 10 + 5
15
> var a = [ 1, 2, 3];
undefined
> a.forEach(function(v) {
... console.log(v);
... });
1
2
3
> var http = require('http');
undefined
> http
[ a massive 'http' object returned from the 'http' module ]

Press control-c twice to exit REPL.

Executing a JS program

So lets write and execute some code in a file! In your working directory:

? mkdir first-node
? cd first-node
? touch main.js
? echo "console.log('hello world');" >> main.js
? node main.js
hello world

Questions?

Now lets talk about modules...

Node.js Modules

Using modules in Node allow us to partition functionality.

Node itself comes with several core modules, such as http that we used earlier. These core modules however, are pre-compiled into binary code and kept in Node's lib/ folder.

Getting Started

Let's open our first-node folder in our favorite text editor. We're going to write a little program to compute the area and circumference of a circle.

// main.js

// load our circle module
var circle = require('./my-modules/circle.js');  // the .js is optional

The above code will:

  • Load the circle.js file as a module
  • Assign what the circle module exports to our circle variable. Note that our variable name could be anything, but it's customary to use a variable with the same or similar name as the module's filename (without the js of course).
  • We can put our module files anywhere, we just have to specify the path.

Create the circle Module

We are loading our circle.js module from a nested folder named my-modules. Lets create both of those:

? mkdir my-modules
? cd my-modules
? touch circle.js

If we cd .. back to first-node, type node main (the .js is optional), Node will run our program. Nothing will happen, but at least we are loading our circle module without errors!

Modules exports Functionality

Inside of our modules, Node automatically provides a special object named exports. We can use the exports object to create our properties - and never forget, properties can be methods.

When we use require to load our module, whatever we added to the exports object is then available on the variable that we assigned our require to.

Adding Functionality to our circle Module

Our goal is to be able to use our circle module to compute both the area and circumference of a circle. Sounds like we need a couple of functions!

// circle.js

exports.area = function (r) {
  return Math.PI * r * r;
};

exports.circumference = function (r) {
  return 2 * Math.PI * r;
};

Questions?

Using our circle Module

With our module's functionality coded, lets write some code in our main.js to try it out:

// main.js

// load our circle module
var circle = require('./my-modules/circle.js');

console.log(circle.area(4));
console.log(circle.circumference(6));

Then node main to validate our module's functionality!

Build a Basic Web Server

So earlier, just for kicks, we used REPL to require Node's http module. Now we're going to use it to build a simple web server.

Back in our main.js, lets replace the code currently in there with this:

var http = require('http');

var server = http.createServer(function(request, response) {
    console.log('Got a request..');
    console.log(request);
    response.write('Thank you for your request!');
    response.end();
});

server.listen(3000, function() {
    console.log('Listening on port: ' + server.address().port);
});

Lets review what's going on here:

  • We used require to include Node's http module and assigned it the http variable.
  • We called http's createServer() method which takes a callback function.
  • We assigned the object returned by the createServer() method to the server variable.
  • We called this "server's" listen method, passing in the port number (3000) we want to listen on.
  • listen will continuously accept requests and call our callback function where we console.log out the request object, and use the write() method on the response object that was passed in to the callback function.
  • Lastly, we send back the response to the client by calling the end() method.

Congrats, you just built a basic web server with Node.js!

Exercise

  1. Research Node's built-in fs package.
  2. Modify main.js to require it.
  3. Create a text file and put some sample text in it.
  4. Change the callback function inside of the createServer method to read your text file and send the contents as the response.

References

Node.js Homepage

scotch.io's MEAN Machine eBook

Blocking/Non-Blocking, Async/Sync

Node Event Loop

Essential Questions

What technology stack is Node.js a huge part of?
[The MEANStack]

Was Node.js written using in JavaScript?
[No, it is written using compiled languages, primarily C++]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment