Run function in script from command line (Node JS)

前端 未结 11 478
情书的邮戳
情书的邮戳 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:59

    Sometimes you want to run a function via CLI, sometimes you want to require it from another module. Here's how to do both.

    // file to run
    const runMe = () => {}
    if (require.main === module) {
      runMe()
    } 
    module.exports = runMe
    

提交回复
热议问题