【问题标题】:How to break this Node code into different files如何将此节点代码分解为不同的文件
【发布时间】:2014-11-18 06:09:56
【问题描述】:

我想放诸如

之类的代码
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

【问题讨论】:

    标签: javascript node.js refactoring


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多