简体   繁体   中英

How to break this Node code into different files

I want to put code such as

app.use("/localAssets", express.static(__dirname + '/localAssets'));
app.use("/scripts", express.static(__dirname + '/scripts'));

in a different file, right now it is in the main server file but I do not like that. I also don't like that all the scoket event handling is also in the main server file.

ie

function onSocketConnection(client) {
  //player connected
  // Listen for client disconnected
  client.on("disconnect", onClientDisconnect);
  client.on('sendMessage', function (data) {
    this.broadcast.emit('message', data);
    this.emit('message', { text: data.text});   
  });   
  // Listen for new player message
  client.on("new player", onNewPlayer);
  // Listen for move player message
  client.on("move player", onMovePlayer);
  client.on("update health", onUpdateHealth);
  client.on("attack hits", onHitByAttack);
  client.on("meteor cast", onMeteorCast)
};

 function onClientDisconnect() {
     ...
 }

Please advise!

Here is the full file I want to sort out:

https://gist.github.com/hassanshaikley/337e5b7b7a8206a54418

Just put anything you want into different files inside of a function like this:

module.exports = function() {
  // your code here
};

Then require and call that function, passing in whatever reference it may need, such as app :

// my-file.js
module.exports = function(app) {
  // your code here
};

// index.js
require('./path/to/my-file')(app);

Here's a basic example of moving routes into another file:

// index.js
require('./path/to/some-routes')(app);

// some-routes.js
module.exports = function(app) {
  app.get('/foo', function(req, res) {
    res.send('Hi! This is foo.');
  });
  app.get('/bar', function(req, res) {
    res.send('Hi! This is bar.');
  });
  app.get('/:me', function(req, res) {
    res.send('Hi! This is '+req.params.me);
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM