Search code examples
node.jscoffeescriptorganization

What's the best way to organize a node project


I am working on a pretty big node project and I am wondering if my current method of requiring files then setting global variables within them (to be accessed everywhere) is a good idea or is it unsafe. I'm wondering if you guys can give me some times.

Server.Coffee

#require and define all dependencies
require 'coffee-script'
GLOBAL.fs = require 'fs'
GLOBAL.crypto = require 'crypto'
GLOBAL.hound = require 'hound'
GLOBAL.async = require 'async'

require './config'
require './functions'

#define route
require './routes/index'
require './routes/login'
require './routes/editor'

#sockets
require './sockets/chat'

console.log "Listening"

config.coffee

GLOBAL.express = require 'express'
GLOBAL.http = require 'http'
GLOBAL.ect = require 'ect'
GLOBAL.mysql = require 'mysql'
GLOBAL.sass = require 'connect-sass'
GLOBAL.coffeescript = require 'connect-coffee-script'
GLOBAL.SchemaObject = require 'node-schema-object'

GLOBAL.User = new SchemaObject
  id: Number,
  fullname: String,
  secret: String,
  email: String,
  lastOpened: Number

GLOBAL.ectRenderer = ect
  watch: true, 
  root: "#{__dirname}/views"

MemoryStore = express.session.MemoryStore
sessionStore = new MemoryStore()  
GLOBAL.app = express()
app.configure ->
  app.use(require('prerender-node'))
  app.use(coffeescript(src: "#{__dirname}/public"))
  app.use '/css/main.css', sass.serve("#{__dirname}/sass/main.scss")
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({secret: 'LOLLYU83rhf99fefru9d', store: sessionStore}));
  app.use express.static("#{__dirname}/public")

GLOBAL.server = http.createServer(app).listen(8080)
GLOBAL.io = require('socket.io').listen(server)

GLOBAL.connection = mysql.createConnection
  host: '.....',
  user: '.....',
  password: '.....',
  database: '.....'

connection.connect()

is there a better way to do this. I feel like I have just guessed and made this up. I want everything to be super neat. and fast.


Solution

  • Ditch all that GLOBAL stuff. If you need app to be available in an inner closure (like configure) just use it there, it will be available.

    Make sure you have a good grasp of closures before continuing, this SO post will help: How do JavaScript closures work?.

    If you want to know how to layout an Express app (as in where do the files go), take a look at this SO post: express.js sample apps.