L
L
LemanRass092017-01-18 02:30:56
Node.js
LemanRass09, 2017-01-18 02:30:56

How to properly build module connection hierarchy in node.js?

Hello.
I have problems with understanding the correct connection of modules and the distribution of code across files.
I work in WebStorm and so far I have a simple http server using express and socket.io.
Judging by the information that I myself managed to find on the Internet, there should be the main script to be launched, in the routes folder there should be js scripts, one for each page that will be displayed in the browser, in the views folder there should also be templates, one for each page, and in the public folder there should be those things that are intended for the client, like css styles and client js scripts.
My main script looks like this:

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var debug = require('debug')('skinsgrow:server');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var steam = require('steam-login');
var io = require('socket.io').listen(server);


server.listen(3000);
server.on('error', onError);
server.on('listening', onListening);


var index = require('./routes/index');
var roulette = require('./routes/roulette');


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(require('express-session')({ 'resave': false, 'saveUninitialized': false, 'secret': 'a secret' }));
app.use(steam.middleware({
    realm: 'http://localhost:3000/',
    verify: 'http://localhost:3000/verify',
    apiKey: '*****************************'
}));

app.use('/', index);
app.use('/roulette', roulette);


app.use('/auth', steam.authenticate(), function (req, res) {
    res.redirect('/roulette');
});
app.use('/verify', steam.verify(), function (req, res) {
    res.redirect('/roulette');
});

app.use('/logout', steam.enforceLogin(), function(req, res){
    res.redirect('/');
});


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(new Error(404, 'Not Found'));
});

// error handler
app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});


/**
 * Event listener for HTTP server "error" event.
 */
function onError(error) {
    if (error.syscall !== 'listen') {
        throw error;
    }

    var bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            console.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;
        case 'EADDRINUSE':
            console.error(bind + ' is already in use');
            process.exit(1);
            break;
        default:
            throw error;
    }
}

/**
 * Event listener for HTTP server "listening" event.
 */
function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    debug('Listening on ' + bind);
}

module.exports = app;

Suppose I needed to use, for example, the socket.io package that is defined in the main app.js script from one of the additional js files from the routes folder.
Wouldn't it be considered bad manners to include the main (running) script in all additional ones?
If so, then how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2017-01-18
@LemanRass09

// modulewithio.js
module.exports = function(io) {
/* use main io object */
}

var io = require('socket.io').listen(server);
var modulewithio = require('modulewithio')(io);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question