Skip to content

Instantly share code, notes, and snippets.

@branneman branneman/app.js
Last active Apr 30, 2019

Embed
What would you like to do?
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.');
@lekhnath

This comment has been minimized.

Copy link

commented Jun 11, 2014

I loved it.

@wlingke

This comment has been minimized.

Copy link

commented Jul 3, 2014

This works well on my mac and windows. Can't get it to work on a linux sadly.

@laurent22

This comment has been minimized.

Copy link

commented Jul 9, 2017

To pass the arguments to the wrapped node.js script, add this after settings the args:

var processArgs = process.argv.splice(2);
args = args.concat(processArgs);

To pass on the exit code of the wrapper process, add this at the end:

app.on('close', (code) => {
	process.exit(code);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.