在单独的文件中共享公共常量和日志功能

xpt*_*xpt 1 javascript constants node.js ecmascript-6

使用相同的NodeJS项目在不同文件之间共享常量有哪些选择?

我正在关注, https://www.reddit.com/r/javascript/comments/3bo42p/sharing_constants_in_es6_modules/

$ cat  constants.js
const ALABAMA  = 1;
const ALASKA = 3;
const ARIZONA =4;
Run Code Online (Sandbox Code Playgroud)

更新,其他详细信息已删除,因为它不是一个很好的例子,我可以遵循我的具体问题.

同样,沿着同一条线,

我希望使用这个软件包,https://www.npmjs.com/package/brolog拥有通用日志工具

但是,我发现在index.js文件中初始化它并不足以让所有其他文件都使用它.

const brolog = require('brolog')
const log = new brolog.Brolog()

const logLevel = process.env['MY_LOG']

if (logLevel) {
  log.level(logLevel)
  log.verbose('Config', 'Log Level set to %s', logLevel, log.level())
}
Run Code Online (Sandbox Code Playgroud)

我不想在我的所有NodeJS文件中重复上述所有设置.

那么,如何在同一个NodeJS项目中的不同文件之间共享公共常量和日志功能?

PS.这只是一个小而简单的项目,我不想为此引入/使用像commonJS这样的大型npm模块.

Ric*_*ick 6

Node.js中应用程序范围常量和实用程序函数的常见模式是为它们创建模块,实例化/设置您需要的任何内容并在您需要的地方使用该模块,例如:

common.js:

'use strict'

module.exports = {
  /**
   * The const of Alabama.
   *
   * @const {number}
   */
  ALABAMA: 1,

  /**
   * The const of Alaska.
   *
   * @const {number}
   */
  ALASKA: 3,

  /**
   * The const of Arizona.
   *
   * @const {number}
   */
  ARIZONA: 4,

  logLevel: process.env['MY_LOG'],
  log: new brolog.Brolog()
}
Run Code Online (Sandbox Code Playgroud)

然后require在任何需要使用公共常量和/或效用函数或类的地方:

app.js:

const common = require('common')

if (common.logLevel) {
  common.log.level(common.logLevel)
  common.log.verbose('Config', 'Log Level set to %s', common.logLevel, common.log.level())
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以并且通常鼓励简化您的实用程序功能,以使它们更方便使用(但不是更简单,不必要):

更多定制的common.js:

'use strict'

const logger = new brolog.Brolog()

module.exports = {
  /*
   ... constants ...
  */

  // more describing
  isLogging: process.env['MY_LOG'],

  // shorthand for leveling
  level: common.log.level,

  // shorthand for verbose logging
  verbose: common.log.verbose,

  // shorthand for warn logging
  warn: common.log.warn,

  // shorthand for error logging
  error: common.log.error
}
Run Code Online (Sandbox Code Playgroud)

app.js中使用:

const common = require('common')

if (common.isLogging) {
  common.verbose('...')
  common.warn('...')
  common.error('...')
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢.适合使用NodeJS的用户<ver 10. Upvoting. (2认同)
  • 还给你一个+1,很棒的答案!如果可以的话,这种模式就是你应该这样做的方式! (2认同)