[NJS] Server, templates and the pipeline
As I said in my previous post, I will do a suite of posts regarding the migration of my website from ruby to Node.js, and to make them easier to spot, I will prefix them with [NJS]. Small warning: I'm not a semicolon user. I've read quite a bit about it, and I made my choice knowingly.
So, the first thing I picked was Express, a really nice web application framework. All it takes to have it running is:
var app = require('express')()
app.get('/', function(req, res) {
res.render('index', { name: 'Roland' })
})
app.listen(process.env.PORT || 3000)
app.set('view engine', 'ejs')ejs is a framework for JS templates, which looks for files in a views folder, at the root of your project. You can combine JS with pure HTML, just like you can combine ruby with it in erb:
<!DOCTYPE html>
<html>
<body>
Hello <%= name >!
</body>
</html>Next, the assets pipeline: Mincer. I kinda like Sprockets, so this was an obvious choice:
var Mincer = require('mincer')
var pipeline = new Mincer.Environment()
Mincer.logger.use(console)
pipeline.appendPath('lib/assets/javascripts')
pipeline.appendPath('assets/stylesheets')
pipeline.appendPath('assets/images')
app.use('/assets', Mincer.createServer(pipeline))Now you can access your assets directly, without remembering how many ../ you need to add to reach it:
<link rel="stylesheet" href="/assets/font-awesome/css/font-awesome.min.css">
<img src="/assets/misc/image.png" alt="Image"/>Coincidentally enough, Express was inspired by Sinatra, Mincer by Sprockets and ejs is just like erb. Funny thing is that the only one I knowingly picked due to this reason was Mincer.
Next time I will write about routes.