Skip to content

Instantly share code, notes, and snippets.

Last active Feb 5, 2021
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 = [
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.set('views', __basedir + '/app/views/');
app.set('view engine', 'html');
// Set middleware
app.use('/static', express.static(__basedir + '/app/static/'));
// Set routes
// Set error handlers
// Start server
console.log('Listening on port ' + config.server.port);
console.log('Use Ctrl+C or SIGINT to exit.');
Copy link

lekhnath commented Jun 11, 2014

I loved it.

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.

Copy link

laurent22 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) => {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment