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

node.js module.export

node.js module.export

Problem

I'm struggling to understand what I am missing here:

FILE: Sprite.js
function Sprite() {
}

Sprite.prototype.move = function () {
}

module.exports = Sprite;

FILE: Ship.js
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
}

FILE: Server.js
var util    = require('util'),
io  = require('socket.io'),
Sprite  = require('./sprite.js'),
Ship    = require('./ship.js');

var boo = new Ship(Sprite);

Outside of Node.js this works fine. In Node.js however it won't recognise Sprite in the ship file. I've tried using module.export = Sprite at the end of the sprite file with no success.

Cheers

Problem courtesy of: Chris Evans

Solution

Export Sprite in FILE: Sprite.js like this :

function Sprite() {
}

Sprite.prototype.move = function () {
}
exports.Sprite = Sprite;

Then inside FILE: Ship.js ( this is the tricky part you're missing ) use require to require the Sprite like this:

var Sprite = require('/path/to/Sprite');
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
}

If a module exports smth, if you whant to use it then you need to require it (in the module you're trying to play with it, not in the main module) don't you?, how else is nodejs going to know where the ship ''class'' is ? more info here


Edit, see this working ( all files need to be in the same directory or you'll need to change the require path )

File sprite.js :

var Sprite = function () {
}
Sprite.prototype.move = function () {
    console.log('move');
}
module.exports = Sprite;

File ship.js :

var Sprite = require('./sprite');
function Ship() {
}

Ship.prototype = new Sprite();

Ship.prototype.enable = function() {
    console.log('enable');
}

module.exports = Ship;

File main.js :

var Ship = require('./ship');

var boo = new Ship();

boo.move();
boo.enable();

Run the example using node main.js and you should see :

C:\testrequire>node main.js
move
enable
Solution courtesy of: Poelinca Dorin

Discussion

View additional discussion.



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

Share the post

node.js module.export

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×