JavaScript: how to include a file in a way that will work either on node.js and on the browser?

I am writting a file that is going to be usable either in the browser and on node.js. To use a library, I could import it using _ = require('underscore.js'); main(); on node, and $.getScript('underscore.js',function(){ main(); }); on the browser. What is the right way to include a file that will work on both environments?

You could use an AMD compliant module loader such as RequireJS.

http://requirejs.org/

Try object detection:

if($ && $.getScript){
    $.getScript('underscore.js',function(){ main(); });
}else if(require){
    _ = require('underscore.js');
}else{
    /* output: Could not load library 'underscore.js'. */
}

A danger with this is that require may be defined but means something else.