require() files that do not use module structure?

45 views
Skip to first unread message

deitch

unread,
Sep 20, 2011, 10:25:08 AM9/20/11
to nodejs
I am looking for some way to require() (or otherwise load) files that
do not conform to the module structure. This is primarily useful when
using 3rd-party client-side libraries that do not have a module
structure, but has other uses as well.

When I do require(), it loads the file with module (and hence
module.exports = {}), and module.exports is returned to the require()
call.

It would be useful if I could find some way to require() an arbitrary
file, pass it any number of arbitrary vars, and then take those vars
as well as "this" from inside the file/pseudomodule.

E.g. if require() had an options array, I could do:

specialVar = {};
foo = require('./somefile.js',{specialVar: specialVar});

Inside the file, it expects specialVar (e.g. window, if it is a client-
side lib) to be available, populates it, even gives a context to
"this". I can then see what specialVar is set to be the library, or
even look at foo.specialVar or foo._this (special variable that
references "this" inside the file) to extract data that I need.

This allows me to have a fully functioning module that does not
conform to the node modules standard, provided I call it with the
correct environment.

Thoughts? Is there any way to do this now?

mscdex

unread,
Sep 20, 2011, 7:15:15 PM9/20/11
to nodejs
On Sep 20, 10:25 am, deitch <a...@deitcher.net> wrote:
> Thoughts? Is there any way to do this now?

http://nodejs.org/docs/v0.4.12/api/vm.html

Matt

unread,
Sep 20, 2011, 7:25:48 PM9/20/11
to nod...@googlegroups.com
And a usage example:


--
Job Board: http://jobs.nodejs.org/
Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com
To unsubscribe from this group, send email to
nodejs+un...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Dominic Tarr

unread,
Sep 20, 2011, 8:54:50 PM9/20/11
to nod...@googlegroups.com
if the module assigns it's functions to the global `this` it will still be available out side.

but that's a bad pattern.

deitch

unread,
Sep 21, 2011, 3:06:02 AM9/21/11
to nodejs
OK, very cool, don't know how I missed it... probably because I did
everything with clean modules until now.

@Matt, @mscdex: thank you very much.

This really does make for a clean bridge when needed.

deitch

unread,
Sep 21, 2011, 3:06:59 AM9/21/11
to nodejs
Actually, I think doing anything from outside files using anything
other than clean modules is probably a bad pattern, but is sometimes a
necessary evil. This piece can save me days of work in converting
something that may not be converted so well in the first place.
Reply all
Reply to author
Forward
0 new messages