首页 文章

MEAN Stack App结构

提问于
浏览
0

我使用express-generator npm为MEAN Stack应用程序创建了一个样板,它工作得很好,但我不明白一些文件的用途 .

例如:

package.json 包含以下代码:

"script":{"start": "node ./bin/www"}

该应用程序包含一个名为 bin 的文件夹,其中包含一个名为 www 的文件,其中包含以下代码:

#!/usr/bin/env node

/**
 * Module dependencies.
 */

 var app = require('../app');
 var debug = require('debug')('myapp:server');
 var http = require('http');


  var port = normalizePort(process.env.PORT || '3000');
  app.set('port', port);

  var server = http.createServer(app);

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

  function normalizePort(val) {
     var port = parseInt(val, 10);

    if (isNaN(port)) {
         // named pipe
           return val;
     }

   if (port >= 0) {
       // port number
       return port;
      }

      return false;
    }

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

 function onListening() {
   var addr = server.address();
   var bind = typeof addr === 'string' ?
     'pipe ' + addr :
     'port ' + addr.port;
      debug('Listening on ' + bind);
    }

Now Im not sure whats the purpose of this because I removed all this code above and added the following lines in my app.js file where my server is:

var port = process.env.PORT || 8080;
app.listen(port);
console.log("Listening on port " + port)

By replacing all that code with only two lines I was able to run the server and display a view using routes. Thats how I have been developing all my node/express apps for a while and they have worked fine.

任何人都可以解释所有代码的重点是什么,因为我不确定它的作用是什么?当我们可以简单地用2行代替它时,为什么需要呢?它似乎非常混乱和不必要 .

1 回答

  • 1

    在package.json文件中,行 "script":{"start": "node ./bin/www"} 告诉节点启动应用程序的位置 .

    您删除的代码包括错误检查并验证服务器正在侦听规范化端口并运行 .

    行: server.on('error', onError); 创建一个绑定到 onError 方法的事件侦听器 . 检测到错误时,将调用并执行 onError() 方法,从而引发错误 .

    同样, server.on('listening', onListening); 创建一个绑定到 onListening 方法的事件侦听器 . 当服务器实际侦听规范化端口时,将调用并执行 onListening() 方法 .

    生成的代码和代码之间的最大区别在于它提供了错误处理,而您的代码却没有 . 错误处理是 absolutely essential and should not be removed if you intend to push your project into a live environment .

    它为您的应用程序提供了一种方法,可以为您提供更好的错误信息(帮助解决问题/调试),并在不完全崩溃的情况下处理问题 . 如果您的应用程序没有启动或崩溃,但您没有内置错误处理或报告,则有时可能会发现问题非常繁琐 .

相关问题