Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active February 5, 2021 21:58
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save branneman/8775568 to your computer and use it in GitHub Desktop.
Save branneman/8775568 to your computer and use it in GitHub Desktop.
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
Copy link

I loved it.

@wlingke
Copy link

wlingke commented Jul 3, 2014

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

@laurent22
Copy link

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