gpt4 book ai didi

javascript - 使用模块构建 node.js 应用程序

转载 作者:搜寻专家 更新时间:2023-11-01 00:24:57 25 4
gpt4 key购买 nike

我想用模块构建我的 Node.js 应用程序。例如,我使用 bunyan 作为记录器。

我有一个文件 main.js

//configs
var logfile = __dirname + '/log.txt';

//my own modules
var log = require("./modules/log"),
init = require("./modules/init");

所以我将日志文件 + 路径传递给日志模块。

我的 log.js

var bunyan    = require('bunyan');

function init(logfile){

var log = bunyan.createLogger({
name: "myapp",
streams: [{
path: logfile
}]
});
return log;
};

module.exports.init = init;

而 init.js 目前只捕获未捕获的异常:

var logging = require('./log'),
log = logging.init;

process.on('uncaughtException', function(err) {

//print to console
console.error((new Date).toUTCString() + ' uncaughtException:', err.message);
console.error(err.stack);

//print to bunyan logger
log.error((new Date).toUTCString() + ' uncaughtException:', err.message);
log.error(err.stack);

});

我现在的主要问题是我想在每个模块中使用记录器。但是当我这样做的时候

var logging = require('./log'),
log = logging.init;

在每个文件中,它每次都会创建记录器。我只想初始化一次,然后在每个模块中使用它。

我想删除记录器的功能:

日志.js

var bunyan    = require('bunyan');
var log = bunyan.createLogger({
name: "juntidos",
streams: [{
path: logfile
}]
});

当我加载模块时,它只会被调用一次。但是我怎样才能传递文件名参数呢?

最佳答案

So I´m passing the log file + path to the log module.

我看到您在 require 日志模块之前定义了 logfile,但与浏览器中的 JavaScript 不同,默认情况下,Node.js 变量不是全局变量。

您的日志文件路径对您的任何模块都不可见。


如果您想 (1) 初始化您的记录器,以便它可以在您的整个应用程序中使用,并且 (2) 传递日志文件名称而不是将其硬编码到您的 log.js 模块中,一种方法是这样做:

// log.js

var bunyan = require('bunyan');

module.exports = {
logger: undefined,

init: function(logfile) {
this.logger = bunyan.createLogger({
name: 'myapp',
streams: [{
path: logfile
}]
});
}
};

现在,您只需确保 init() 被恰好调用一次,并且发生在 加载任何其他模块之前。这应该很容易:

// main.js

var logfile = __dirname + '/log.txt';

var log = require('./modules/log.js').init(logfile), // init() called here
anotherModule = require('./modules/anotherModule.js')
someOtherModule = require('./modules/someOtherModule.js');

在你的子模块中,这样做:

// someOtherModule.js

var log = require('./log.js');
log.logger.warn('someOtherModule was loaded');

关于javascript - 使用模块构建 node.js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com