node Module.runMain listOnTimeout 严重占用CPU的问题。(第一次发起提问)
发布于 7小时前 作者 mlinquan 45 次浏览 来自 问答

图片是用node-inspector调试的结果。 结果CPU占用最多是在编译和执行和加载模块上。 百思不得其解,望大家帮忙。

20150807150204.jpg

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

global.Q = require('q');

//遍历列出模块名
var ListingModules = require('./tools/ListingModules');

//验证POST请求的数据
global.validateData = require('express-validatefilter');
global.validator = require('validator');

//时间格式化模块
global.moment = require('moment');

/* 加载路由 */
var routes = new ListingModules('./routes');
var routes_list = {};

/* 加载API */
var APIs = new ListingModules('./api');
global.API = {};
APIs.list.forEach(function(api) {
    var path = APIs.rel_list[APIs.list.indexOf(api)];
    path = path.replace('/', '');
    API[path] = require(api);
});

/* Session */
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var session_conf = {
  db: {
    db: 'session',
    host: '127.0.0.1',
    port: 27017,  // optional, default: 27017
    //username: 'admin', // optional
    //password: 'secret', // optional
    collection: 'sessions' // optional, default: sessions
  },
  secret: 'nani?'
};

/* mongodb & 数据模型 Schemas */
global.mongoose = require('mongoose');
global.mongodb = require('mongodb');
mongoose.connect('mongodb://127.0.0.1:27017/mox');
var schemas_list = new ListingModules('./Schemas');
global.Schemas = {};
schemas_list.list.forEach(function(schemas) {
    var path = schemas_list.rel_list[schemas_list.list.indexOf(schemas)];
    path = path.replace('/', '');
    Schemas[path] = require(schemas);
});

/* 模板引擎 */
global.cons = require('consolidate');
global.nunjucks = require('nunjucks');

global.middleware = require('./routes/fallback');
var routes_global = require('./routes/global');
var routes_index = require('./routes/index');
var routes_api = require('./routes/api');
var routes_join = require('./routes/join');
var routes_login = require('./routes/login');
var routes_fallback = require('./routes/fallback');
var routes_user_center = require('./routes/user_center');

/* ----------------------------- App主体部分开始 ----------------------------- */ 
var app = express();

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'views/img', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

/* 使用Session */
app.use(session({
    resave: false,
    saveUninitialized: true,
    secret: session_conf.secret,
    maxAge: new Date(Date.now() + 3600000),
    store: new MongoStore(session_conf.db)
}));

/* 设置模板引擎 */
app.engine('html', cons.nunjucks);
/* 设置 .html 为模板文件默认扩展名 */
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

/* 加载静态文件目录 */
app.use('/js', express.static(__dirname + '/views/js'));
app.use('/css', express.static(__dirname + '/views/css'));
app.use('/images', express.static(__dirname + '/views/images'));
app.use('/img', express.static(__dirname + '/views/img'));
app.use('/fonts', express.static(__dirname + '/views/fonts'));
//app.use('/views', express.static(__dirname + '/views'));

/* 使用路由 */
app.use('*', routes_global);//全局数据有效性验证
app.use('/join', routes_join);//注册
app.use('/login', routes_login);//登录
app.use('/', routes_index);//首页
app.use('/api', routes_api);//前端API接口
app.use('/user_center', routes_user_center);//用户中心
app.use('*', routes_fallback);//兜底

/*routes.list.forEach(function(route) {
    var path = routes.rel_list[routes.list.indexOf(route)];
    if(path == '/index') {
      path = '/'
    }
    routes_list[path] = require(route);
    console.log(path);
    app.use(path, routes_list[path]);
});*/

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

// error handlers

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

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

/**
 * Module dependencies.
 */

var debug = require('debug')('Moxent:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

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

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

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

/**
 * Normalize a port into a number, string, or false.
 */

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

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

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

  return false;
}

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

//app.listen(3000);
//console.log('Express server listening on port 3000'); \n```
回到顶部