I am writing a multiplayer board game server in NodeJS, and I have several different objects like Game, User, Board etc. Currently, all of these objects reside in a single 'sever.js' file which is executed by NodeJS.
As my project grows, this single file is becoming increasingly crowded and hard to navigate.
What I would like is to split these objects into multiple js files, but without having to开发者_运维百科 use the require function all over the place.
I wish to continue creating objects like this -
game = new Game();
And not this -
game = new (require('game')).Game()
--
Edit:
What is the correct NodeJS way of doing things?
Well, there are a few small things you can do.
First, when you define your class in another file (to be required) you define module.exports
directly, i.e.
module.exports = function Game() {...};
And, then instead of:
game = new (require('game')).Game()
You can do:
game = new (require('game'));
Or, what I prefer, is to define all the requirements at the top:
var Game = require('game'),
User = require('user');
// Use them:
new Game();
new User();
You could create some fancy loader that traverses the directly and automatically requires all JS files, but I really don't think it's worth it.
You can use global. in Game.js:
global.Game = function(){};
in User.js:
global.User = function(){};
in main.js:
require('Game.js');
require('User.js');
var game = new Game();
var user = new User();
You can load them at the beginning:
var Game = require('game').Game;
// Do a bunch of stuff
var game = new Game();
However, I personally wouldn't. Can't say exactly why I don't like the idea, but I don't.
精彩评论