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?
How about testing for the existence of the
exportsobject before sticking stuff in it?This has worked well for me so far, but maybe there are better ideas out there:
In CoffeeScript, this can be done a little more tersely: