Run function in script from command line (Node JS)

前端 未结 11 493
情书的邮戳
情书的邮戳 2020-12-07 07:25

I\'m writing a web app in Node. If I\'ve got some JS file db.js with a function init in it how could I call that function from the command line?

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 07:56

    This one is dirty but works :)

    I will be calling main() function from my script. Previously I just put calls to main at the end of script. However I did add some other functions and exported them from script (to use functions in some other parts of code) - but I dont want to execute main() function every time I import other functions in other scripts.

    So I did this, in my script i removed call to main(), and instead at the end of script I put this check:

    if (process.argv.includes('main')) {
       main();
    }
    

    So when I want to call that function in CLI: node src/myScript.js main

提交回复
热议问题