ChrisRich ChrisRich - 3 months ago 18
Node.js Question

Route efficiency

In my production app I'm using a

require
statement inside each route handler. I was wondering if I might take a performance hit?

How it works now:

app.get('/', require('../templates/views/home'))
app.get('/foo', require('../templates/views/foo'))
app.get('/bar', require('../templates/views/bar'))


How it could be working in the next release:

var views = require('../templates/views')

app.get('/home', views.home)
app.get('/foo', views.foo)
app.get('/bar', views.bar)


And obviously
/templates/views.js
would export all views using a
require
statement but only a single time when the application starts.

Does it even make a difference?

Answer

There's no difference from a performance perspective, but it's considered poor style to use requires freely throughout your code since it makes it difficult to identify dependencies.

Also, using requires in your code like that will make it much more difficult to transition to ES6 imports since they don't evaluate to inline expressions.

// JS
var views = require('../templates/views')

app.get('/home', views.home)
app.get('/foo', views.foo)
app.get('/bar', views.bar)

// ES6
import views from '../templates/views';

app.get('/home', views.home)
app.get('/foo', views.foo)
app.get('/bar', views.bar)

// This won't work...
app.get('/home', import 'home' from '../template/views/home');