简体   繁体   English

Node.js将命令行参数设置为常量

[英]Nodejs set command line argument as constant

I want to get an argv from my command line when I am going to start my server and then I want to set it as a constant for a module. 当我要启动服务器时,我想从命令行获取argv,然后将其设置为模块的常量。

For example I want to define my log file path from commandline: 例如,我想从命令行定义日志文件路径:

My starter.js looks like: 我的starter.js看起来像:

var optimist = require("optimist");
var server = require("./start_server");
var argv = optimist.describe('logpath', 'logptah for info').argv;
server.init({logpath:argv.logpath});

My start_server.js looks like: 我的start_server.js看起来像:

    var restify = require('restify');
    var server = restify.createServer({
        name: 'dummy-project'
    });
    module.exports.logpath = null;
    function init(args){
        server.listen(1234, function() {
            console.log("inside logs");
            console.log(args.logpath);
            module.exports.logpath = args.logpath;
            console.log('%s listening at %s', server.name, server.url);
        });
    };
    module.exports.init = init;
    var fun = require('./common/loghandler');

My loghandler.js looks like: 我的loghandler.js看起来像:

var server = require('./../start_server');
console.log("inside log handler");
var LOGPATH = server.logpath;
console.log(LOGPATH);

When I am running node starter.js --logpath='../../custom/info.txt' I am not getting the logpath inside my loghandler. 当我运行node starter.js --logpath='../../custom/info.txt'我的node starter.js --logpath='../../custom/info.txt'

Seems logpath handler is called before the server.listen. 似乎在server.listen之前调用了日志路径处理程序。

The console output looks like: 控制台输出如下所示:

node starter.js --logpath='../../custom/info.txt'
inside log handler
null
inside log handler 
../../custom/info.txt
dummy-project listening at http://0.0.0.0:1234

How I can overcome it and pass my log path as command line argument? 我该如何克服它,并将日志路径作为命令行参数传递?

Thanks in advance. 提前致谢。

Your init() function is executed after starter.js uses require('./start_server') . starter.js使用require('./start_server')之后执行init()函数。 When you use require() , the file and all its dependencies are loaded. 使用require() ,将加载文件及其所有依赖项。 That means during this process, you also executed require('./common/loghandler') , which completes before server.init() is run in starter.js . 这意味着在此过程中,您还执行了require('./common/loghandler') ,该过程在starter.js运行server.init()之前完成。 Since server.logpath hasn't been set by this time, you get a null value. 由于此时尚未设置server.logpath ,因此将获得空值。

Aside from that, module.exports is set at require time and changing the values later have no effect. 除此之外, module.exports是在需要的时间设置的,以后更改值无效。 To fix the problems you're having, you should avoid using functions before your application has fully loaded, and put return values in your modules. 为了解决您遇到的问题,应避免在应用程序完全加载之前使用函数,并将返回值放入模块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM