solotimes
2/2/2014 - 10:01 PM

Node.js application entry-point files

Node.js application entry-point files

#!/usr/bin/env node

'use strict';

var spawn = require('child_process').spawn;

var args = [
  '--harmony',
  'app/bootstrap.js'
];

var opt = {
  cwd: __dirname,
  env: (function() {
    process.env.NODE_PATH = '.'; // Enables require() calls relative to the cwd :)
    return process.env;
  }()),
  stdio: [process.stdin, process.stdout, process.stderr]
};

var app = spawn(process.execPath, args, opt);
// Load external dependencies
const express  = require('express');
const mongoose = require('mongoose');
const swig     = require('swig');

// Load app dependencies
const config      = require('app/config.json');
const controllers = require('app/controllers');

// Connect to database
mongoose.connect(config.db.url, {server: {socketOptions: {keepAlive: 1}}});
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));

// Set global __basedir to the directory of the application entry-point file
global.__basedir = resolve(__dirname, '../');

// App & view configuration
var app = express();
swig.setDefaultTZOffset((new Date).getTimezoneOffset());
app.engine('.html', swig.renderFile);
app.disable('x-powered-by');
app.disable('etag');
app.set('views', __basedir + '/app/views/');
app.set('view engine', 'html');

// Set middleware
app.use(express.compress());
app.use('/static', express.static(__basedir + '/app/static/'));

// Set routes
controllers.admin.defineRoutes();
controllers.frontend.defineRoutes();
controllers.api.defineRoutes();

// Set error handlers
app.use(controllers.errorHandler.status404);
app.use(controllers.errorHandler.status500);

// Start server
app.listen(config.server.port);
console.log('Listening on port ' + config.server.port);
console.log('Use Ctrl+C or SIGINT to exit.');