javascript - 如何将此 Node 代码分解为不同的文件

标签 javascript node.js refactoring

我想输入诸如

之类的代码
app.use("/localAssets", express.static(__dirname + '/localAssets'));
app.use("/scripts", express.static(__dirname + '/scripts'));

在另一个文件中,现在它位于主服务器文件中,但我不喜欢这样。我也不喜欢所有 scoket 事件处理也在主服务器文件中。

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() {
     ...
 }

请多多指教!

这是我要整理的完整文件:

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

最佳答案

只需将您想要的任何内容放入函数内的不同文件中,如下所示:

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

然后 require 并调用该函数,传入它可能需要的任何引用,例如 app:

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

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

以下是将路由移至另一个文件的基本示例:

// 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);
  });
};

关于javascript - 如何将此 Node 代码分解为不同的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26987750/

相关文章:

c# - 如何模拟shift/ctrl/alt键状态?

javascript - 如何使用 url 中的 "#q"重定向 "?q"

javascript - $() 不是调用模态对话框谷歌地图调整大小的函数

javascript - node.js mongodb 通过_id node-mongodb-native 选择文档

c# - 用于处理表单中嵌入的自定义类

c# - 在 ASP.NET MVC 解决方案中从我的域对象重构表示代码的最佳方法是什么?

c# - 如何将两种方法转换为一种方法以提高效率?

javascript - 无法读取未定义的属性 '0' 以及如何选择 r = magnum 的数据?

node.js - Loopback <model>.verify 不是函数\n

node.js - 通过管道传输同一流两次会产生无限循环