🟢 Node

Updated at 2015-07-25 16:41

This guide contains basic syntax and tips how to write Node.js code. You should have some experience with JavaScript to understand these fully. I have is a separate coding guide for JavaScript.

Node.js is a platform to build network applications using JavaScript. It is not a framework like Rails or Django, it is one level lower. Related to JavaScript guide and JavaScript testing.

  • Node is fitting in data-intensive real-time web applications because easy to use WebSockets between server and browser JavaScript.
  • Node is useful in web applications because you can share implementation details with server and client, e.g., template rendering can first be done once on the server.
  • Node is appropriate when latency might cause waiting because of event-driven programming.
  • Node has no significant benefits for simple web pages. Most of the time you will be better off with something else than Node.
  • Doing anything math heavy in Node and JavaScript should be avoided as there are plenty of pitfalls. You can do it, but you need to be careful.

Install Node with version manager software. If you are working on multiple projects, they can easily use different Node versions. Version manager makes updating and changing versions a breeze.

brew install nvm    # install Node Version Manager
nvm ls              # list locally installed Node versions and shows the active
nvm ls-remote       # list Node versions available for installation
nvm install v9.8.0  # install a specific Node version
nvm use 9           # use a specific Node version for this console until closed

Don't use Node.js for everything. Use a reverse proxy e.g. nginx. In this context, reverse proxy is a service that redirects requests to another service inside the internal network e.g. in the same machine.

Use nginx for SSL termination, allows usage of SSL acceleration hardware.
All heavy encryption should be done outside Node.js
Don't bind directly to 80/443
    Easier to enable gzip or add SSL certificate.

Creating a simple web server:

// Load http-module.
var http = require('http');

// Initialize the web server.
var server = http.createServer();

// When server event `request` happens, do
// something with `request` to figure out what the request is for
// and finally use `response` to specify how to respond to the request.
server.on('request', function(request, response) {
  response.write('Hello, this is dog.');

// When server event `close` happens...
server.on('close', function() {
  console.log('Shutting down...')

// Start listening to port 80 for requests.