Suggestions for working with `export` in node.js

Theory:

One of the things that I like about node.js uses it as a command line tool.

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

For example, I have text.js in ~/.node_libraries, and he's got a bunch of text related functions that I use over and over again ( depunctuate(), tokenize_text(), things like that).

The beauty is that I can use the same file text.jswith my command line and server side scripts. Right now I am doing everything that processes text using Python, but I would like to just stick to one language.

Practice:

AFAICT, to create a node.js module, I have to bind everything that I want to be accessible exportsor this. Ie, in text.js, I have to do:

exports.depunctuate = depunctuate

or

this.depunctuate = depunctuate

If I use exports, I am having problems using the server side library à la:

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

because then I get the export is not defined .

If I use this, I avoid error, but everything that I export becomes attached to the window object.

Is there any way to configure these libraries to avoid both of these problems? For example, is there a way to export exportsso that var is explicit to the node, but not when it was used in the Javascript file on the server?

+5
2

exports , ?

, , , :

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

CoffeeScript :

[exports.foo, exports.bar] = [foo, bar] if exports?
+7

. , === (). :

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

All Articles