简体   繁体   中英

Suggestions for dealing with `exports` in node.js

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 . Ie, 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 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?

so this comes into a namespacing issue. Unless a function is called with the new operator you will get a this context === to window (global). A way to dodge this is:

(function( exports ) {
  /* put your depuncuate definition here to keep it from leaking to the global */
  exports.depunctuate = depunctuate;
})( (typeof exports === 'undefined') ? myAppNamespace : exports );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM