N
N
No_Time2013-06-26 19:09:58
JavaScript
No_Time, 2013-06-26 19:09:58

Node.JS how best to organize the export of an asynchronous function from a module? (coffeescript)

Good time of the day!

I sat down to write a project generator on node.js, express, coffee, etc. There are a great many of them, but everywhere they don’t like something, either the routing is inconvenient, or the configs cannot be set in files, in general, everything is not right. I want to be able to initiate the launch of an express server with a callback in the root app.coffee. I thought for a long time how to describe it in Russian better - I didn’t think of it, I’ll try to explain with examples:

The following module is connected to app.coffee

engine = require './app/engine'


Inside it, in turn, the following happens:
express = require 'express'
http = require 'http'
app = express()

###
# Много страшной настройки express
###

# Вот тут все коряво, надо как-то исправлять
module.exports = 
  app: app
  start: (done) ->
    http.createServer(app).listen app.get('port'), -> done true    # WTF: неужели нет другого способа?


The monster export above allows you to write the following in app.coffee:
engine.start -> print "Awesome server listening on port " + engine.app.get('port')


Those. I really want to be able to write in the console that the server has successfully started, and write it from app.coffee.

Is it possible to implement this somehow more elegantly? Do not throw slippers into coffee, far from special) Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lastwish, 2013-06-27
@lastwish

Why http? And what exactly is "inelegance"?
I would improve so:
1) Removed http;
2) Removed a separate method for returning app ;
3) I would not pick out the configs (in this case, the port) from the app inside the module, but would store
engine.coffee separately there:

express = require 'express'

app = express()
port = process.env.PORT or 5000

exports = module.exports = (callback) ->
  app.listen port, callback

app.coffee:
engine = require './engine'

app = engine -> 
  console.log "listening on " + app.address().port

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question