Welcome!

Apache Authors: Mark R. Hinkle, Carmen Gonzalez, Roger Strukhoff, Liz McMillan, Elizabeth White

Blog Feed Post

The Absolute Beginner’s Guide to Node.js

An absolute Beginner's Guide to node.js – by Brandon Cannaday

This is a republished blog post by Brandon Cannaday. Brandon is the CTO of Modulus, a Node.js application hosting platform. Brandon organizes the Indianapolis Node.js meetup and enjoys speaking at conferences about Node’s horizontal scalability. Prior to Modulus, Brandon worked in the chemical detection and telecommunications industries.

Modulus is the first company in the industry to offer a dedicated enterprise solution called Curvature. Curvature allows you to take advantage of rapid deployments, easy scaling, and real-time analytics in the environment of your choosing, on-premises, in the cloud, or a hybrid of the two.


There’s no shortage of Node.js tutorials out there, but most of them cover specific use cases or topics that only apply when you’ve already got Node up and running. I see comments every once and awhile that sound something like, “I’ve downloaded Node, now what?” This tutorial answers that question and explains how to get started from the very beginning.

What is Node.js?

A lot of the confusion for newcomers to Node is misunderstanding exactly what it is. The description on nodejs.org definitely doesn’t help.

An important thing to realize is that Node is not a webserver. By itself it doesn’t do anything. It doesn’t work like Apache. There is no config file where you point it to you HTML files. If you want it to be a HTTP server, you have to write an HTTP server (with the help of its built-in libraries). Node.js is just another way to execute code on your computer. It is simply a JavaScript runtime.

Installing Node

Node.js is very easy to install. If you’re using Windows or Mac, installers are available on the download page.

I’ve Installed Node, now what?

Once installed you’ll have access to a new command called “node”. You can use the node command in two different ways. The first is with no arguments. This will open an interactive shell (REPL: read-eval-print-loop) where you can execute raw JavaScript code.

$ node
> console.log('Hello World');
Hello World
undefined

An absolute Beginner's Guide to node.js – Hello World

In the above example I typed “console.log(‘Hello World’)” into the shell and hit enter. Node will then execute that code and we can see our logged message. It also prints “undefined” because it displays the return value of each command and console.log doesn’t return anything.

The other way to run Node is by providing it a JavaScript file to execute. This is almost always how you’ll be using it.

hello.js

console.log('Hello World');
$ node hello.js
Hello World

An absolute Beginner's Guide to node.js – console

In this example, I moved the console.log message into a file then passed that file to the node command as an argument. Node then runs the JavaScript in that file and prints “Hello World”.

File I/O with node.js

Running plain JavaScript is fun and all, but not very useful. This is why Node.js also includes a powerful set of libraries (modules) for doing real things. In this first example I’m going to open a log file and parse it.

example_log.txt

2013-08-09T13:50:33.166Z A 2
2013-08-09T13:51:33.166Z B 1
2013-08-09T13:52:33.166Z C 6
2013-08-09T13:53:33.166Z B 8
2013-08-09T13:54:33.166Z B 5

What this log data means is not important, but basically each message contains a date, a letter, and a value. I want to add up the values for each letter.

The first thing we need to do it read the contents of the file.

my_parser.js

// Load the fs (filesystem) module
var fs = require('fs');

// Read the contents of the file into memory.
fs.readFile('example_log.txt', function (err, logData) {

// If an error occurred, throwing it will
  // display the exception and end our app.
  if (err) throw err;

// logData is a Buffer, convert to string.
  var text = logData.toString();
});

Fortunately Node.js makes file I/O really easy with the built-in filesystem (fs) module. The fs module has a function named readFile that takes a file path and a callback. The callback will be invoked when the file is done being read. The file data comes in the form of a Buffer, which is basically a byte array. We can convert it to a string using the toString() function.

Now let’s add in the parsing. This is pretty much normal JavaScript so I won’t go into any details.

my_parser.js

// Load the fs (filesystem) module.
var fs = require('fs');// 

Read the contents of the file into memory.
fs.readFile('example_log.txt', function (err, logData) {

// If an error occurred, throwing it will
  // display the exception and kill our app.
  if (err) throw err;

// logData is a Buffer, convert to string.
  var text = logData.toString();

var results = {};

// Break up the file into lines.
  var lines = text.split('\n');

lines.forEach(function(line) {
    var parts = line.split(' ');
    var letter = parts[1];
    var count = parseInt(parts[2]);

if(!results[letter]) {
      results[letter] = 0;
    }

results[letter] += parseInt(count);
  });

console.log(results);
  // { A: 2, B: 14, C: 6 }
});

Now when you pass this file as the argument to the node command it will print the result and exit.

$ node my_parser.js
{ A: 2, B: 14, C: 6 }

An absolute Beginner's Guide to node.js – my_parser.js

I use Node.js a lot for scripting like this. It’s much easier and a more powerful alternative to bash scripts.

Asynchronous Callbacks in node.js

As you saw in the previous example, the typical pattern in Node.js is to use asynchronous callbacks. Basically you’re telling it to do something and when it’s done it will call your function (callback). This is because Node is single-threaded. While you’re waiting on the callback to fire, Node can go off and do other things instead of blocking until the request is finished.

This is especially important for web servers. It’s pretty common in modern web applications to access databases. While you’re waiting for the database to return results Node can process more requests. This allows you to handle thousands of concurrent connections with very little overhead, compared to creating a separate thread for each connection.

Create a HTTP Server with node.js

Like I said before Node doesn’t do anything out of the box. One of the built-in modules makes it pretty easy to create a basic HTTP server, which is the example on the Node.js homepage.

my_web_server.js

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080);

console.log('Server running on port 8080.');

When I say basic, I mean basic. This is not a full-featured HTTP server. It can’t serve any HTML file or images. In fact, no matter what you request, it will return ‘Hello World’. However, you can run this and hit http://localhost:8080 in your browser and you’ll see the text.

$ node my_web_server.js

You might notice something a little different now. Your Node.js application no longer exits. This is because you created a server and your Node.js application will continue to run and respond to requests until you kill it yourself.

If you want this to be a full-featured web server, then you have to do that work. You have to check what was requested, read the appropriate files, and send the content back. There’s good news, though. People have already done this hard work for you.

Express for node.js

Express is a framework that makes creating most normal websites very simple. The first thing you have to do it install it. Along with the node command you also have access to a command called “npm”. This tool gives you access to an enormous collection of modules created by the community, and one of them is Express.

$ cd /my/app/location
$ npm install express

When you install a module, it will put it in a node_modules folder inside your application directory. You can now require it like any built-in module. Let’s create a basic static file server using Express.

my_static_file_server.js

var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/public'));

app.listen(8080);
$ node my_static_file_server.js

You now have a pretty capable static file server. Anything you put in the /public folder can now be requested by your browser and displayed. HTML, images, almost anything. So for example, if you put an image called “my_image.png” inside the public folder, you can access it using your browser by going to http://localhost:8080/my_image.png. Of course Express has many many more features, but you can look those up as you continue developing.

NPM

We touched on npm a little in the previous section, but I want to emphasize how important this tool will be to normal Node.js development. There are thousands of modules available that solve almost all typical problems that you’re likely to encounter. Remember to check npm before re-inventing the wheel. It’s not unheard of for a typical Node.js application to have dozens of dependencies.

In the previous example we manually installed Express. If you have a lot of dependencies, that’s not going to be a very good way to install them. That’s why npm makes use of a package.json file.

package.json

{
  "name" : "MyStaticServer",
  "version" : "0.0.1",
  "dependencies" : {
    "express" : "3.3.x"
  }
}

A package.json file contains an overview of your application. There are a lot of available fields, but this is pretty much the minimum. The dependencies section describes the name and version of the modules you’d like to install. In this case I’ll accept any version of Express 3.3. You can list as many dependencies as you want in this section.

Now instead of installing each dependency separately, we can run a single command and install all of them.

$ npm install

When you run this command npm will look in the current folder for a package.json file. If it finds one, it will install every dependency listed.

Code Organization in node.js

So far we’ve only been using a single file, which isn’t very maintainable. In most applications your code will be split into several files. There’s no standard or enforced organization to what files go where. This isn’t Rails. There’s no concept of views go here and controllers go there. You can do whatever you want.

Let’s re-factor the log parsing script. It’s much more testable and more maintainable if we separate out the parsing logic into its own file.

parser.js

// Parser constructor.
var Parser = function() {

};

// Parses the specified text.
Parser.prototype.parse = function(text) {

var results = {};

// Break up the file into lines.
  var lines = text.split('\n');

lines.forEach(function(line) {
    var parts = line.split(' ');
    var letter = parts[1];
    var count = parseInt(parts[2]);

if(!results[letter]) {
      results[letter] = 0;
    }

results[letter] += parseInt(count);
  });

return results;
};

// Export the Parser constructor from this module.
module.exports = Parser;

What I did was create a new file to hold the logic for parsing logs. This is just standard JavaScript and there are many ways to encapsulate this code. I chose to define a new JavaScript object because it’s easy to unit test.

The important piece to this is the “module.exports” line. This tells Node what you’re exporting from this file. In this case I’m exporting the constructor, so users can create instances of my Parser object. You can export whatever you want.

Now let’s look at how to import this file and make use of my new Parser object.

my_parser.js

// Require my new parser.js file.
var Parser = require('./parser');

// Load the fs (filesystem) module.
var fs = require('fs');

// Read the contents of the file into memory.
fs.readFile('example_log.txt', function (err, logData) {

// If an error occurred, throwing it will
  // display the exception and kill our app.
  if (err) throw err;

// logData is a Buffer, convert to string.
  var text = logData.toString();

// Create an instance of the Parser object.
  var parser = new Parser();

// Call the parse function.
  console.log(parser.parse(text));
  // { A: 2, B: 14, C: 6 }
});

Files are included exactly like modules, except you provide a path instead of a name. The .js extension is implied so you can leave it off if you want.

Since I exported the constructor that is what will be returned from the require statement. I can now create instances of my Parser object and use it.

Summary

Hopefully this tutorial can bridge the gap between downloading Node.js and building your first widget. Node.js is an extremely powerful and flexible technology that can solve a wide variety of problems.

I want everyone to remember that Node.js is only bound by your imagination. The core libraries are very carefully designed to provide the puzzle pieces needed to build any picture. Combine those with the modules available in npm and it’s amazing how quickly you can begin building very complex and compelling applications.

If you have any questions or comments, feel free to drop them below.

Codeship – A hosted Continuous Deployment platform for web applications

Now you know how to get started with node.js why don’t you head over to Codeship and set up Continuous Deployment your first node.js project?

Read the original blog entry...

More Stories By Manuel Weiss

I am the cofounder of Codeship – a hosted Continuous Integration and Deployment platform for web applications. On the Codeship blog we love to write about Software Testing, Continuos Integration and Deployment. Also check out our weekly screencast series 'Testing Tuesday'!

@ThingsExpo Stories
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at Internet of @ThingsExpo, James Kirkland, Chief Architect for the Internet of Things and Intelligent Systems at Red Hat, will describe how to revoluti...
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.