Modularising your own Code When Node.js was being developed, JavaScript will still predominantly a browser-only technology and had no support for modules. Node. js based their module system on the CommonJS standard for JavaScript modules. The require function syntax for loading other JavaScript packages is what we have as a result. To make the JavaScript module system work, any code you write that you intend to import in another file should explicitly export the bits of code that the other files should have access to. An “official” standard module system is now in development for JavaScript which is similar conceptually but with a slightly different syntax. The Node.js convention for JavaScript modules is that any data or function that you attach to the module.exports property can be imported when you use require on that file. Let’s create a simple file to demonstrate all of this: const PI = 3.14159; exports.add = function(x, y) { return x + y;} // In the following we use the new // arrow function syntax for brevity exports.multiply = (x, y) => x * y; exports.circleArea = (r) => PI * r * r; Let’s say this code is in a file called math.js in the same directory as your main code. You could then import this using: const math = require(‘./math’); Note that the .js extension is not required. Now the functions defined in the above code will be available under the math object. So you could run them as math.add(1, 3) or math.circleArea( 4). The PI constant will not be available however, as it is not explicitly attached to export. If a directory contains a index.js file then you can use require on that directory itself. This index. js file can then import other files from that directory allowing better organisation and encapsulation of your code. In the case of packages (i.e. folders with a package.json file) you can specify which file should be imported when that package the “main” field in the package.json file. Creating A Simple Web Service Let’s get our hands dirty by creating a simple web app which converts an absolute date into a relative date. So given a date like 11-02- 2017 it will say something like “in 2 years”. To build this app we will use two very popular packages. The first is HAPI, which is “A rich framework for building applications and services”. The other is library called “moment” that lets you work with dates and times, and includes the ability to compare date. While HAPI is a pure Node.js package that is designed to run on the server side, moment is pretty much a JavaScript library that can run in the browser or on Node.js. You should start by creating a directory for this project, and running npm init in it. Just stick with the defaults by pressing Enter at all the prompts. With this done you should install the packages we mentioned by running the following two commands: $ npm install –save hapi $ npm install –save moment Finally create a file called index.js in which you can place the following code: ‘use strict’; const Hapi = require(‘hapi’); const moment = require(‘moment’); const server = new Hapi.Server(); server.connection({ port: 3000 }); server.route({ method: ‘GET’, path: ‘/when/{date}’, handler: function (request, reply) { reply(moment(request.params.date, “DD-MM-YYYY”). fromNow()); } }); server.start(); Explaining the intricacies of creating Hapi apps is out of the scope of this article, but here’s the gist of what’s happening here: • We first import both the libraries we need. • We create a new Hapi server that will run out app. • We specify that this server will use port 3000 • We set up a route on this server which can be accessed at ‘/ when/’ followed by the date • We have some code that is run whenever someone visits such a URL • We start the server The function that is run when someone visits our app with a date simply uses the moment library to convert a data string in the format ‘DD-MM-YYYY’ into a date object, and then we use moment’s fromNow method to convert this into a relative date. This is sent back as a reply to the browser. If you now run this index.js using node, you will be able to open this app in your browser at http://localhost:3000/ or http://127.0.0.1:3000/. That particular page has nothing to show and will probably show a 404 error, however if you visit a URL like http://localhost:3000/when/02-11-2017 you should see the browser display the simple text ‘in 2 years’. Unless of course you are reading this in the future and it shows ‘in 1 year’ or ‘2 years ago’. Funny how relative, relative dates can be.
Our HAPI-based web app running in Firefox. We’ve zoomed it in here to make it more visible.
Conclusion There is a lot to like about Node.js other than simply reusing JavaScript for server-side development. Many of the architectural decisions made by Node.js make it especially good for handling a large number of connections and in handling real-time web applications. Even if you only want to develop browser-based client-side applications and don’t want to use JavaScript on the server side, knowing a bit about Node.js and npm can be a huge help. There are tonnes of tools like gulp, grunt and webpack that make it easy to set up a pipeline for handling complex web applications.