Run function in script from command line (Node JS)

前端 未结 11 440
情书的邮戳
情书的邮戳 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 08:07

    If your file just contains your function, for example:

    myFile.js:

    function myMethod(someVariable) {
        console.log(someVariable)
    }
    

    Calling it from the command line like this nothing will happen:

    node myFile.js
    

    But if you change your file:

    myFile.js:

    myMethod("Hello World");
    
    function myMethod(someVariable) {
        console.log(someVariable)
    }
    

    Now this will work from the command line:

    node myFile.js
    
    0 讨论(0)
  • 2020-12-07 08:08

    I do a IIFE, something like that:

    (() => init())();
    

    this code will be executed immediately and invoke the init function.

    0 讨论(0)
  • 2020-12-07 08:11

    simple way:

    let's say you have db.js file in a helpers directory in project structure.

    now go inside helpers directory and go to node console

     helpers $ node
    

    2) require db.js file

    > var db = require("./db")
    

    3) call your function (in your case its init())

    > db.init()
    

    hope this helps

    0 讨论(0)
  • 2020-12-07 08:14

    Update 2020 - CLI

    As @mix3d pointed out you can just run a command where file.js is your file and someFunction is your function optionally followed by parameters separated with spaces

    npx run-func file.js someFunction "just some parameter"
    

    That's it.

    file.js called in the example above

    const someFunction = (param) => console.log('Welcome, your param is', param)
    
    // exporting is crucial
    module.exports = { someFunction }
    

    More detailed description

    Run directly from CLI (global)

    Install

    npm i -g run-func
    

    Usage i.e. run function "init", it must be exported, see the bottom

    run-func db.js init
    

    or

    Run from package.json script (local)

    Install

    npm i -S run-func
    

    Setup

    "scripts": {
       "init": "run-func db.js init"
    }
    

    Usage

    npm run init
    

    Params

    Any following arguments will be passed as function parameters init(param1, param2)

    run-func db.js init param1 param2
    

    Important

    the function (in this example init) must be exported in the file containing it

    module.exports = { init };
    

    or ES6 export

    export { init };
    
    0 讨论(0)
  • 2020-12-07 08:15

    Simple, in the javascript file testfile.js:

    module.exports.test = function () {
       console.log('hi');
    };
    this.test();
    

    Running at the prompt:

    node testfile.js
    
    0 讨论(0)
提交回复
热议问题