Node.js for .NET Developers

Introduction

You can pick up the solution from https://github.com/johnconraddomingo/NodeJs.AspnetNodejs

This whole post is a good introduction to Node.js from a .NET Developer’s perspective. By the end of this document, you should

  • Be familiar with Node.js
  • Get your hands wet with Node.js JavaScript
  • Be abel to build a very basic HTML Hello World website
  • Be able to build an API

We will not build anything too pretty because as i’d like to limit the scope of this post, but we will be able to create a HTML Website and a WebAPI.

It is assumed that

  • You know your way around Visual Studio
  • You know the basics of a website
  • You have an idea what MVC is

What is it?

The official definition is Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. To explain that further:

  • You write Server-side codes that run on Chrome’s V8 engine. That said, js codes are actually compiled, and only expressed as Javascript. This is in contrast to the Javascript that you would write in a browser, which is interpreted script.
  • You most likely write Client-Side scripts on Javascript, and so you will most likely be dealing with Javascript and JSON both Server-Side and Client-Side
  • Non-blocking IO simply means Asynchronous operations, that is, when you make a request to the server, it doesn’t block any other incoming requests.
  • V8 provides a predictable environment for developers. Unlike Javascript that you write on a browser, Node.js runs on a platform with not much variables that will affect its dependencies.

I am primarily a .NET Developer, and so majority of what will be discussed here is (a) how Node.js compares with ASP.NET and (b) using Visual Studio to code.

Comparing Node.js and ASP.NET

For starters, they both have a dot in their names… Does that count?

  • Asynchronous Operations: Although ASP.NET allows for this, Node.js provides this functionality out of the box
  • Language used: ASP.NET can be expressed using C# or VB, and whatever language is available for .NET, including F#. On the other hand, Node.js is expressed in Javascript.
  • Compilation: Just because Node.js is expressed in Javascript, it means that it’s not compiled and that it’s slower compared to ASP.NET which is compiled into assemblies. Node.js is compiled. Javascript is merely the language used.
  • Power: Node.js, by definition is fast and efficient. However, it is not used for more intensive stuff that require much processing power.
  • Package Manager: While .NET as a whole has Nuget (https://www.nuget.org/), Node has NPM (https://www.npmjs.com/) or Node Package Manager.
  • Engine: ASP.NET uses the .NET Framework as the engine while Node.js uses V8.
  • Views: ASP.NET Provides View Engines with either ASPX or Razor available out of the box. They’re pretty much the same with very little difference in syntax. In Node.js, we work with View Engines that we can get from NPM. Since you’re reading a blog for .NET Developers, it’s best to use Vash, being a Razor clone.

Let’s start!

Starting Node.js

Getting Node.js

Downloading for Usage

We can download Node.js from https://nodejs.org/en. It will detect your machine for you. You can go ahead and download what link is available, or go to https://nodejs.org/en/download/ for more options.

Preparing your development from Visual Studio

From Visual Studio, create a New Project and you’ll find Node.js Web Application from the Templates list under JavaScript. This should get you started with a Web Server running.

NodeNewProject

Note: Please make sure you download the package from https://nodejs.org/en, otherwise Visual Studio will hang up when you create a new Project.

What you’re getting

Now, let’s see what Visual Studio created for you.

‘use strict’;
var
http = require(‘http’);
var
port = process.env.PORT || 1337;
http.createServer(function (req, res) {
res.writeHead(
200, { ‘Content-Type’: ‘text/plain’ });
   
res.end(‘Hello World\n’);
}).listen(port);

You get a port that Nodejs opens for you and a createServer method that accepts self-executing method.

It writes Hello World in the Response as a plain text, which you can easily replace with an application/json if you’re doing a WebAPI.

Let’s go through them in the next sub sections

Running from the Console

You’ll notice that a console is running everything: It’s just opening a port an accepting a request and returning something. If you’re running on production , there are a few solutions out there that will allow you to install it as a service, like os-service (https://www.npmjs.com/package/os-service) and node-windows (https://github.com/coreybutler/node-windows)

You’ll also notice that it’s starting up from server.js: You can find that this file is set in the package.json file located in the root folder of your project

“name”: “node-js.aspnet-nodejs”,
“version”: “0.0.0”,
“description”: “NodeJs.AspnetNodejs”,
“main”: “server.js”,
“author”: {
   
“name”: “John”
}

Dependencies

Now, dependencies. In .NET (and most other frameworks out there), it is the framework that handles the dependencies by looking at the folder structure and going through each file and looking at the classes available.

Node.js is quite different in that it expects you to point to it where the dependencies are, sort of like how C++ works. Here, it’s via the require keyword and in the sample above it’s using the http module.

How to Point to your Dependencies

Here’s an introduction on how to use the require/exports keyword to link them all up. Here’s what my project looks like

NodeJsProject

I created a folder named modules. That’s where I want to put all my custom methods. I can group files that are relevant to each other based on what they do, and even put them in the root folder. But for the purpose of this blog, I used a straightforward name.

Under it, I created a numberSquared and a personInfo file. They’re javascript files, as opposed to cs or vb if you’re coming from .NET. We will call these exposed objects from our server.js.

Fields

I want my personInfo to return a static value, and so I’m going to use the exports keyword and return an anonymous class to a named field that i’m going to call person.

module.exports.person = { id: 0, firstName: “John Conrad”, lastName: “Domingo” };

Back at server.js, I say

// Require: Field
var staticPersonInfo = require(‘./modules/personInfo.js’);
console.log(‘Test >> Default Person is ‘ + JSON.stringify(staticPersonInfo.person));

Where I just call .person like a normal field.

Method

It’s pretty much the same concept for methods, but this time I’m going to tell the exports keyword to take a self-executing anonymous method and say that squared will return the number * number.

module.exports = function (number) {
   
return { squared: function () {
      
return number * number;
      
}
    }
;
}

Back at server.js I do the same thing by requiring a numberSquared and this time, I will get 25 by calling the squared() method.

// Require: Method
var simpleMath = require(‘./modules/numberSquared.js’);
console.log(‘Test >> The square of 5 is ‘ + simpleMath(5).squared());

Method Structure

You will find that the default method structure of self-executing methods come in the form of request/response: And that’s because of the asynchronous nature of Node.js. It doesn’t hang around to wait for things to finish. It lets go of control and executes the callback once it does its job.

Packages

This section will use the package express (https://www.npmjs.com/package/express) as an example. Express is a web framework that we will be using later on.

Getting Packages

You can pick up Packages from npm where the command options get installed along with Node.js. You can visit the site on https://www.npmjs.com/. You can easily access the Package Manager from the command prompt. This is the .NET equivalent of Nuget where you can download Packages via Powershell.

To install from Visual Studio using the Command Prompt, Right-click on your project and choose Open Command Prompt here. Or you can just go to the Command Prompt yourself and manually go your project folder. and type

npm install express –save

where express is the name of the package that you want to install and –save says that you want to add express as a dependency to the package.json file, allowing it to automatically be downloaded.

You can also do it via Visual Studio. From the npm node in Solution Explorer, right-click and choose Install New npm Packages.

Either method you choose, you will find that a folder named node_modules will be populated by the package that you installed as well as its dependencies.

Using Packages

To use a package, simply refer to it via the require keyword. Easy! Node.js should already know all about your dependencies since it’s already in your package.json file. Visual Studio even lists your packages from the NPM package properties under Solution Explorer.

var express = require(‘express’);

At this point, even Visual Studio offered express to me via Intellisense

Web API

Now, we’re going to make an API. You know that an API is merely a Controller and that if we want to build a website out of that, we’ll basically reuse this method and chuck in a View and Controllers

Refer to the codes below. I once again used the require keyword and pulled in express. Express has functions that corresponds to HTTP verbs, like get, post and delete. And from there, we add in self-executing methods that returns either a HTML string for a website or json (plus xml, potentially).

This set how your calls to the server is routed. You should be very familiar with this as we have it either in RouteConfig in MVC or as attribute on top of the HTTP methods inside your controller.

var http = require(‘http’);
var
express = require(‘express’);
var
app = express();

// Default
app.get(‘/’, function (req, res) {
    res.send(
‘<html><head></head><body><h1>Hello World</h1></body></html>’);
});

// Api
app.get(‘/api/defaultPerson’, function (req, res) {
   
var staticPersonInfo = require(‘./modules/personInfo.js’);
   
res.set(“Content-Type”, “application/json”);
   
res.send(staticPersonInfo.person);
});

var server = http.createServer(app);
server.listen(1337, function () {
    console.log(
“Express is running on port 1337”);
});

you will notice that from the default get, I passed in HTML. You can in theory build a website out of this, although things would just get silly if you do anything more than a hello world. What you want to do is get a View Engine later on.

NodejsEdge

Now let’s look at the API. I go to api/default and it’s giving me back a json with the person object I pulled in from personInfo.js. Have a look at the header that I added in.

NodejsPostman

If we have a look at the header, it is indeed giving us an application/json as we have defined.

nodejsPostman2

There isn’t much parsing either, because Node.js is already talking json in the backend!

Conclusion

That folks, has been your introduction to Node.js. If you are a .NET developer, this post should be very straightforward to you. If you would like to learn more, it would really help if you do further reading on

  • How Node.js handles the MVC pattern
  • How View Engines get integrated (see: Vash)
  • How Node.js links to static resources
  • How Node.js handles data management (see: MongoDB)
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s