node.js库的多次初始化很好吗?

时间:2016-03-15 02:25:15

标签: node.js

我正在使用node.js和winston,mongodb等库。我将nodejs拆分为多个文件,以便于维护,如index.js,user.js,posting.js,database.js,logging.js等。

logging.js如下所示:

var config = require('./config'),     
path = require ('path'),
winston = require('winston'),
winstonRotate = require('winston-daily-rotate-file');

winston.level = config.appSetting.winstonLogLevel;

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),  
    new (winstonRotate)({
      name: 'info-file',
      datePattern: '.yyyyMMdd',
      filename: path.join(__dirname, "logs", "info.log"),    
      level: 'info'
    }),
    new (winstonRotate)({
      name: 'error-file',
      datePattern: '.yyyyMMdd',
      filename: path.join(__dirname, "logs", "error.log"),    
      level: 'error'
    }),
    new (winstonRotate)({
      name: 'debug-file',
      datePattern: '.yyyyMMdd',
      filename: path.join(__dirname, "logs", "debug.log"),    
      level: 'debug'
    }),
    new (winstonRotate)({
      name: 'warn-file',
      datePattern: '.yyyyMMdd',
      filename: path.join(__dirname, "logs", "warn.log"),    
      level: 'warn'
    })
  ]
});

module.exports = logger;

database.js

var mongoClient = require('mongodb').MongoClient,    
mongodbObjectID = require('mongodb').ObjectID,
logger = require('./logging'), database;

// Connect to the db
mongoClient.connect(config.appSetting.dbConnectionString, function(err, db) {

  if(!err) {

    database = db;

    logger.info("Connected to DB");

  } else {

     logger.error("Failed to connect to moolahome mongodb : " + err);

     console.dir(err);

     process.exit(1);       
  }

});

module.exports = database;

我将logging.js添加到index.js,user.js和posting.js以及database.js进行日志记录,这导致logger初始化4次。 我将database.js添加到index.js,user.js和posting.js这导致3次初始化数据库。

这是正常还是需要将记录器和数据库设置为单例?

1 个答案:

答案 0 :(得分:0)

首次加载后,所有库(或模块)都缓存在require对象中 Check this out
所以,运行时没问题,确定这是你自己对app结构的决定:)