Building a web service with Node.js in Visual Studio Part 5: npm and Express.js basics


In the previous post we discussed the absolute basics of a Node web application. It really didn’t have a lot of functions: it listened to every single incoming request and responded with some properties of the request. We also come to the conclusion that those functions were quite limited. We have no routes, no controllers, no nothing, so working with code on that level is really cumbersome.

In this post we’ll discuss the package manager of Node i.e. the Node Package Manager npm. We’ll also go through the basics of Express.js which is a web framework built on top of Node.

We’ll build upon the CustomerOrdersApi so have it ready in Visual Studio – or in the IDE of your preference. You can write Node.js in Notepad if you wish, but Visual Studio provides some extras, like debugging, break points, intellisense etc.

Node Package Manager

One element we haven’t discussed so far is the little node called “npm”:

npm node in visual studio

npm stands for Node Package Manager. It is the Node.js equivalent of NuGet in .NET and Maven in Java. It is a tool for managing dependencies that are not part of standard Node.js. E.g. the “http” package we saw previously is included by default so we didn’t have to import it. There are a number of packages that are not installed by default and they need to be imported if you need to use them.

The imported packages will be referenced in the file called package.json, visible in the above screenshot. This function of package.json is similar to pom.xml in a Java Maven project and packages.config in .NET. The dependencies in package.json will be read by the IDE and install the necessary dependencies after opening the project for the first time.

This is valid for Node.js, .NET and Maven as well: it’s not necessary to send the dependencies around to other developers. You can upload the project and package.json to a central source, like SVN or Git. Another developer who downloads it from source control can look into package.json and install the dependencies or let Visual Studio take care of it automatically.

So what external libraries are available? This site lists all of them. Packages are referenced by names such as “grunt”, “express” or “underscore”.

Manual installation

You can call npm in a command prompt. If you open a command prompt and type “npm” then, if you followed the Node.js installation in part 1 then you should get the usage help message of npm:

npm in command window

Close the command prompt, this was just a test to see of “npm” works. Right-click the project name in Visual Studio and click “Open Command Prompt Here”. Enter the following command to install the package called “grunt”:

npm install grunt

If everything goes well then you’ll see that grunt is installed along with all dependencies of grunt:

npm manual install grunt output

The dependencies will be listed under the npm node and stored in a folder called “node_modules”:

grunt visible as dependency in project

However, what’s that “not listed in package json” about? Open package.json and you’ll see nothing about dependencies there, right? This means that you can use grunt in your project but other developers won’t be aware of it just by looking at the package.json file. They will see some reference to it in the code, like request(‘grunt’) and then they’ll need to fetch the dependency via npm themselves.

Let’s uninstall grunt by the following command:

npm uninstall grunt

Grunt will silently disappear from the project.

The –save flag will ensure that package.json is filled in:

npm install grunt –save

Check package.json and you’ll see a field called “dependencies”:

"dependencies": {
"grunt": "^0.4.5"

Uninstall grunt before we continue:

npm uninstall grunt –save

Using the npm tool

There’s a more visual approach to all this. Right-click “npm” in Solution Explorer and select “Install New npm Packages”. This will first load all available packages and then open a window similar to the following:

npm visual tool

Search for “grunt”, click on the package name to select it – the present version of grunt is 0.4.5, you might see something higher – and then click “Install package” leaving all other default values untouched. Grunt will be installed again.

If you right-click npm again then you’ll see options like “Update npm Packages” and “Install Missing npm Packages”. These do exactly what’s expected based on their descriptions: update installed npm packages and install any missing ones based on the package.json file. So another developer who downloads your project can simply run these functions to get the necessary dependencies.

If you right-click the grunt pckage under npm you’ll be able to uninstall it by selecting “Uninstall npm package(s)”.

Installing Express.js

Express.js is a web framework comparable to ASP.NET on top of IIS. It is a dependency that can be downloaded via npm like we did with grunt. Right-click “npm” and select Install New npm Packages. Search for “express” and select the first result that comes up:

ExpressJs package in NPM

By the time you read this post there will almost certainly be an updated package but hopefully there won’t be large code changes. Clicke “Install package” and then Express and its dependencies should be installed:

ExpressJs installed with dependencies

Check package.json as well, “express” should appear in the dependencies array. The node_modules folder was also populated with Express with its own node_modules folder for its dependencies:

ExpressJs in node_modules folder with its dependencies

Using Express.js

Now that we have installed Express.js let’s use it. We’ll go through the statements first and re-write server.js at the end.

The first step is to import Express into our project like we did with “http” using the require method:

var express = require('express');

“express” can be executed like a function and it will return a reference to our application, like in a singleton:

var app = express();

We can take this reference and pass it into the createServer method in place of the current callback. Here’s the current state of server.js:

var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 1337;

The application doesn’t do anything yet but this step was necessary to have Express drive our web app.

Express takes care of requests based on the web methods, like GET, POST etc. and the URL. Express exposes methods to handle the HTTP verbs and the methods are named exactly as those verbs: get, post etc. They accept a URL and a callback function which will be similar to what we had before. Add the following code after app = express():

app.get("/", function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end("<html><body><p>Hello from the application root</p></body></html>");

The above code ensures that we respond to GET requests to the root of the web app which is “/”. Run the application and you should see the message in the browser. You can test other URLs, such as /index, they won’t work, you’ll get an exception message on the screen saying like “Cannot GET [url]”.

Notice that we’re sending HTML back whereas RESTful APIs normally respond with JSON. Let’s see how we can respond with Json. Insert the following code after the get method shown above:

app.get("/customers", function (req, res) {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end('{name: "Great customer", orders: "none yet"}');

Run the application and navigate to /customers. You should see the JSON as shown in the code. There’s in fact a more concise way of sending a response using the “send” method:

app.get("/customers", function (req, res) {
    res.set('Content-Type', 'application/json');
    res.send({name: "Great Customer", orders: "none yet"});

The writeHead method was replaced by the set method. Also, note the lack of apostrophes around the JSON object, i.e. we’re not specifying the JSON as a string. Re-run the app to make sure that everything works. You’ll see the JSON object as string in the browser window. In fact we can even leave out the set method in this case and Express will infer from the object type that we’re sending back a JSON object. However, the set method can be used to put other headers types to the response.

In the next post we’ll look at the module.exports function and controller basics.

View all posts related to Node here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: