Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Include class definition file

Include class definition file

Problem

How can I include a file, which contains classes definitions in my server.js file?

I don't want to use module.exports because I want to use this file in my client javascript Code too.

Thank you!

Problem courtesy of: Tuizi

Solution

If you want the module's contents to be available outside the scope of the file you have to use module.exports. Making the file also work in a browser just requires you to do some extra if/elses

For instance:

var self = {};

// Browser?
if(instanceof window !== 'undefined')
{
    window['my_module_name'] = self;
}
// Otherwise assume Node.js
else
{
    module.exports = self;
}

// Put the contents of this module in self
// For instance:
self.some_module_function = function() {
    // Do stuff
}

Now if you're in Node.js you can reach the function like this:

my_module = require('my_module_name');
my_module.some_module_function(58);

Or if you're in a browser you can just call it directly since it's global:

my_module.some_module_function(58);

Otherwise I can recommend Stitch.js which allows you to develop Javascript Code using the CommonJS style require and modules, then compile it to also run in the browser with no code changes.

Require.js also allows for this type of functionality.

Here's another SO question about using the same code in node and browsers:
how to a use client js code in nodejs

Solution courtesy of: Hubro

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Include class definition file

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×