NodeJS: Use environment variables in front end scripts

I'm writing a socket.io app, and I'm getting annoyed at having to chance a line in my frontend scripts.js file every time I push to heroku, from

var socket = io.connect('http://localhost');

to

var socket = io.connect('http://ersatz-elephant-1337.herokuapp.com/');

I know I can use process.env.VAR to access those variables on the backend, but I'm wondering if there's any way to programmatically determine which to use in my frontend scripts? I'd rather leave the scripts as static aside from this, but maybe that's not possible?

EDIT: I'm not really looking for a solution on the backend... I'm looking for a way that my /public/scripts.js file can connect to the right thing. I guess maybe the only way to do that is by specifying something special in server.js for the frontend script file, rather than serving it statically, but if so, then that's the instruction I'm looking for, not how to actually access the env vars on the server. Sorry for any confusion!

It's very possible. Either use foreman or use a configuration script like this one:

var url = require('url');
var config = {};
var dbUrl;

if (typeof(process.env.DATABASE_URL) !== 'undefined') {
    dbUrl = url.parse(process.env.DATABASE_URL);
}
else {
    dbUrl = url.parse('tcp://postgres:postgres@127.0.0.1:5432/db');
}

config.dialect = 'postgres';
config.protocol = dbUrl.protocol.substr(0, dbUrl.protocol.length - 1); // Remove trailing ':'
config.username = dbUrl.auth.split(':')[0];
config.password = dbUrl.auth.split(':')[1];
config.host = dbUrl.hostname;
config.port = dbUrl.port;
config.database = dbUrl.path.substring(1);

console.log('Using database ' + config.database);
module.exports = config;

I know you asked for a solution using environment variables, however my view is that using runtime parameters is a better solution as it provides better flexibility.

As I stated above, you can then always use a shell script (as appropriate for the OS that your using) to set the runtime params based on environment variables if you so wish.

To use args, you use process.argv. you can do a forEach on this and iterate through the arguments (refer node.js manual process argv). Personally I would use a module. The one I like is called opt. It has lots of nice features and makes processing command line arguments very simple. You can specify defaults, define help messages for each param, etc. It even supports config files. I think you may find this appealing.

However, if you like the KISS approach, then I would suggest using process.argv.

If you are set on utilising environment variables within your script then you can always just use process.env.MY_ENV_VARIABLE where MY_ENV_VARIABLE is the environment variable (refer how to read environment variable in node js).