Caleb Madrigal

Programming, Hacking, Math, and Art

 

Why I changed my mind about Node.js

Intro

I first heard of Node.js about 4 years ago. I thought it was a ridiculous idea: using JavaScript as your server-side language! JavaScript always felt to me like an inferior language. Why would you use it unless you absolutely had to!? Now of course, you have to do JavaScript if you are writing code which runs in the browser, but on the server, you can use any language you choose. So why choose JavaScript?

I did choose to use JavaScript/Node.js on my current project. I have now been using it for the last several months, and I am quite impressed! Let me tell you what made me change my mind about Node.js.

Adoption by the Enterprise world

First, Node.js has been adopted ...

Sessions in Node.js and Express.js

In the process of trying to explain to a friend how sessions work, I decided to write a barebones example to demonstrate how to do sessions in Node.js with Express.js.

Here's a live demo: http://expressjs-session-example.herokuapp.com/

And Here's what it looks like:

Before you enter your name:

After you enter your name:

And here is the code:

var express = require('express');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('cookie-session');

///////////////////////////////////////////////////////////////////////////////////////// MIDDLEWARE

var app = express();

// Needed to handle JSON posts
app.use(bodyParser.json());

// Cookie parsing needed for sessions
app.use(cookieParser('notsosecretkey'));

// Session framework
app.use(session({secret: 'notsosecretkey123'}));

// Consider all URLs under /public/ as static files, and return them raw.
app.use(express.static(__dirname + '/public'));

/////////////////////////////////////////////////////////////////////////////////////////// HANDLERS

function ...