views:

61

answers:

1

Theory:

One of the things that appeals to me about node.js is using it as a command line tool.

In theory, I can write libraries in Javascript and place them in my ~/.node_libraries directory, and then then I can reuse those libraries.

So for instance, I have a text.js in ~/.node_libraries, and it has a bunch of text-related functions I use over and over (depunctuate(), tokenize_text(), things like that).

The beauty of this is that I could use the same text.js file with my command-line scripts and server side. Right now I'm doing all that text processing stuff with Python, but I'd like to just stick to one language.

Practice:

AFAICT, in order to create a node.js module, I have to attach everything that I want to be available to exports or this. I.e., in text.js, I have to do:

exports.depunctuate = depunctuate

or

this.depunctuate = depunctuate

If I use exports, I have problems with using the library server-side à la:

<script src=text.js></script>

because then I get exports is not defined errors.

If I use this, I avoid the error, but everything I export ends up getting attached to the window object.

Is there some way I can set up these libraries that avoid both of these problems? For instance, is there some way I can wrap the exporting of exports so that the var will be apparent to node, but not when it's used in a plain Javascript file on a server?

+2  A: 

How about testing for the existence of the exports object before sticking stuff in it?

This has worked well for me so far, but maybe there are better ideas out there:

if(typeof(exports) !== 'undefined' && exports !== null) {
  exports.foo = foo;
  exports.bar = bar;
}

In CoffeeScript, this can be done a little more tersely:

[exports.foo, exports.bar] = [foo, bar] if exports?
Carlos Villela
That did it! Gotta love Stackoverflow... BTW, why can't I just say `if(exports)`?
pat
Wait, on second thought, I am still able to get to `window.depunctuate`.
pat