“Why are you using Node.js rather than PHP?”

I got this question in the mail today:

Hey.

I noticed (correctly?) that you are using node.js for craftstud.io to serve static files. (That’s how it’s called?)

Why did you pick that over simple php pages, like index.php?page=blah ?
I can guess it might be security, but yet, node.js seems to be a bit of pain to use (?) [at least for somebody who’s not proficient with it?].

Or is that only because you wanted to have paths like…

mysite.com/games/test_game

instead of something like

mysite.com/games?id=test_game

Which would be the PHP solution?

I thought my answer might be of interest to more people so here it is:

Hey,

I did a lot of PHP back in the day but just because that’s what lots of people use doesn’t mean it’s the right choice or even that it’s simpler than another technology.

I don’t necessarily believe a well-written Node.js app is inherently more secure than well-written PHP pages (although one could argue it’s easier to write secure Node.js code than PHP code because the framework and most modules are better designed).

NodeJS logo

I use Node.js with ExpressJS because I find it to be a very productive setup for me. Not so much for static files (I could -and probably should- serve those directly from Nginx/Apache rather than letting Node handle them) but rather for all the sign up / auth / mailing / purchasing / localization logic. Also, using Node.js with ExpressJS lets me use Jade for HTML templating, Stylus for CSS and CoffeeScript for JS, which are much less verbose than their traditional counterpart and I find that very enjoyable.

Jade

Routing (defining URLs) with ExpressJS is very easy indeed. There is no excuse for displaying file extensions in URLs, it’s an implementation detail that the user shouldn’t care about. URLs are a kind of user interface and as such should be kept simple. But you could do something similar in PHP with a bit of URL rewriting (Apache’s mod_rewrite module could help with that) so it’s not a reason per se to switch away from PHP.

app.get('/', function(req, res){
 res.send('hello world');
});

Overall Node.js is a great ecosystem (thanks in no small part to its GREAT package manager), it’s lean and it also allows for some powerful stuff that traditional page-based Web languages like PHP just can’t do (proper long-running apps like real-time multiplayer Web games with socket.io for instance) all the while making the mundane stuff much simpler.

Coding a website with Node.js is a bit more involved than putting together a few PHP pages at first (you have to understand the whole event loop, callbacks and asynchronous stuff) so it might not be the right choice for everyone. I do believe the productivity savings are huge in the long run.

As far as I’m concerned, I dove into Node a few years ago and I haven’t looked back.