Node.js – A Simple Tutorial With Example

Are you’re just starting out with Node.js and looking for a simple example that demonstrates some of its key concepts and benefits? Something that’s a little more complex than “Hello world!” but still easy enough to comprehend? You may know JavaScript but wonder how it can be used as a server-side language. Then you are just like me, when I started with Node.js. Back then I found tons of tutorials and how-to articles that showed how to install Node.js, but almost none that demonstrated its concepts.

That’s what you’ll learn in this article: Apart from what Node.js is and what it is used for, you’ll also see how to use modules to create a simple way to upload files to the server and connect to external programs.

So, let’s dive right into it. For illustration purposes of this short tutorial we’ll tackle the following web development challenge:

How to use Node.js to count the number of lines, words and bytes in a text file.

Here is what we want our initial browser screen to look like:

After clicking the ‘Browse’ button, you can select a text file on your computer. When you hit the ‘Count Now’ button, you’ll receive a result page with the number of lines, words and bytes in the file you had selected:

What Node.js Is Used For

Of course you could use client-side JavaScript to count lines and words, but the point of this article is to demonstrate the architecture, concepts and benefits of Node.js.

What it’s used for in this example: Node.js acts as a web server that responds to HTTP requests. We’ll upload a text file to a remote Node.js server and then process it with server-side Linux shell commands. Node.js has an event-driven and non-blocking architecture to optimize throughput and scalability for real-time web applications.

In many use case scenarios a Node.js server responds to requests by connecting with large and complex asynchronous applications such as databases, game servers, chat servers and other Saas services. (For instance: Our company is using a Node.js server to connect to a predictive analytics application that does real-time optimization of web content.)

And in this simple example the Node.js server functions as such a connector with a typical (drastically simplified) architecture that makes use of modules to execute Node.js-external Linux shell commands.  Here is how the user, control and data flow looks like:

In the first step, a GET request is sent from a user’s browser to our Node.js server which responds by sending an initial HTML page. The HTML form on this page includes an input element that allows uploading a text file via a POST request.

In the second step after the user selects a text file, its content is submitted as a POST request to the Node.js server where it is stored with a temporary filename. Then the Node.js server script spawns an external child process to execute the Linux shell commands ‘wc’ and ‘awk’. ‘wc’ counts the lines, the words, and the number of bytes of the file, while ‘awk’ is used to format the output. After the external executable has finished, the Node.js server delivers the results back to the user’s browser and deletes the temporary file.

Now, before you think this sounds pretty complicated, let me show you the 25 lines of code of “server.js” that makes this all work. Yes, this IS ALL the code that is needed to create this Node.js server:

var express     =    require('express'),
    multer      =    require('multer'),
    app         =    express(),
    exec        =    require('child_process').exec,
    fs          =    require('fs');

  multer({ dest: '/tmp/uploads/' }),
  function(req, res){
    child = exec("wc " + req.files.textfile.path +
                 "| awk {'print \"#lines: \"$1\" | #words: \"$2\" | #bytes: \"$3'}",
                 function(err, stdout) {
                   res.writeHead(200, {"Content-Type": "text/plain"});
                   res.end(stdout.trim() + " | " + req.files.textfile.originalname);

    console.log("Working on port 8080");

This program contains three code segments that are very typical for many Node.js servers.

1. Segment. Module Declaration and Import: Modules, such as express, child_process, fs or multer are libraries that provide powerful functionality that you’d otherwise have to program yourself. So, before you start re-inventing the wheel, make sure you check if there is a module that solves the task at hand. Express, for instance, maps the destination routes in the requesting URLs to functions that can respond to specific request. To make use of a module, you’ll have to install it on your server via npm (more about npm in the resource section at the end) and import it with the ‘require’ function:

var module = require('module');

2. Segment. GET, POST (and other HTTP) Request Actions: A Node.js server’s job is to wait for an event to happen and then do something without blocking anything. So, it’s perfect for implementing RESTful APIs with GET, PUT, POST, DELETE, etc. requests to send JSON encoded data back and forth. In our little example, we process only two requests.

GET request: When our Node.js server receives a GET request on ‘/’, it reads a locally stored HTML file named ‘index.html’ and sends it back as a response.


Here is the complete HTML file that contains the form with a file input element to select and upload the text file. Notice that the action that will occur when pushing the submit button is a POST request to the route ‘/wc':

    <title>node.js - example</title>
      <h1>node.js - count number of lines,<br />
          words and bytes in a text file</h1>
      <form id="uploadForm"
      <input type="file" name="textfile" />
      <input type="submit" value="Count Now" name="submit">

Side note: There are very powerful modules and frameworks available that work hand in hand with Node.js. They allow you to create and manage very large and dynamic HTML repositories and use Node.js as an intelligent web content or streaming server.

POST request: Our little Node.js server is only able to respond to one particular type of POST requests: When a POST request is sent to ‘/wc’ and contains an uploaded file. What happens next is that our responding function uses a module called ‘multer’ to save the transmitted text file locally using a unique, temporary filename. After that the ‘exec’-function, which is part of the ‘child_process’ module, spawns a process that executes the two piped Linux shell commands ‘wc’ and ‘awk’. Eventually the output is formatted and sent back as a response. Finally the temporary file is deleted using the ‘unlink’ function from the ‘fs’ module.'/wc',[
  multer({ dest: '/tmp/uploads/' }),
  function(req, res){
    child = exec("wc " + req.files.textfile.path +
                 "| awk {'print \"#lines: \"$1\" | #words: \"$2\" | #bytes: \"$3'}",
                 function(err, stdout) {
                   res.writeHead(200, {"Content-Type": "text/plain"});
                   res.end(stdout.trim() + " | " + req.files.textfile.originalname);

3. Segment. The Node.js server has to be initiated so that it can start listening for requests on a port you can define. In our case it’s 8080.

    console.log("Working on port 8080");

You got a glimpse in this example that Node.js is not just a server-side platform that runs generic JavaScript. It is supported by very powerful modules and frameworks that go beyond this simple example, ranging from database access, socket communication, file I/O, dynamic web content management and much, much more. That’s what makes Node.js perfect for real-time web application such as game servers, streaming servers, any type of communication servers for web apps and mobile phone apps.


Below I have listed a few resources that will help any novice to hit the ground running.

Q: I have never done anything in Node.js. How and where do I start?
1. Get an Amazon account
2. Set up a node server
3. Install modules using npm

Q: What is npm?
The Node Package Manage allows you to install Node.js module conveniently by taking care of all the necessary changes and dependency.

Q: What is Express?
Express is a web application framework for Node.js.

Q: What are the most common/important modules I should install?
The number and quality of available modules increase on a daily basis.
Go to npm to find the top most downloaded modules.


SEO Strategy & Consulting Firm



More from our blog

See all posts