[javascript] Run function in script from command line (Node JS)

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?

This question is related to javascript node.js command-line

The answer is


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


As per the other answers, add the following to someFile.js

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

You can then add the following to package.json

"scripts": {
   "myScript": "node -e 'require(\"./someFile\").someFunction()'"
}

From the terminal, you can then call

npm run myScript

I find this a much easier way to remember the commands and use them


Try make-runnable.

In db.js, add require('make-runnable'); to the end.

Now you can do:

node db.js init

Any further args would get passed to the init method.


If you turn db.js into a module you can require it from db_init.js and just: node db_init.js.

db.js:

module.exports = {
  method1: function () { ... },
  method2: function () { ... }
}

db_init.js:

var db = require('./db');

db.method1();
db.method2();

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

maybe this method is not what you mean, but who knows it can help

index.js

const arg = process.argv.splice(2);

function printToCli(text){
    console.log(text)
}

switch(arg[0]){
    case "--run":
        printToCli("how are you")
    break;
    default: console.log("use --run flag");
}

and run command node . --run

command line

probuss-MacBook-Air:fb_v8 probus$ node . --run
how are you
probuss-MacBook-Air:fb_v8 probus$ 

and you can add more arg[0] , arg[1], arg[2] ... and more

for node . --run -myarg1 -myarg2


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


I do a IIFE, something like that:

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

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


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

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 };

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to command-line

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Flutter command not found Angular - ng: command not found how to run python files in windows command prompt? How to run .NET Core console app from the command line Copy Paste in Bash on Ubuntu on Windows How to find which version of TensorFlow is installed in my system? How to install JQ on Mac by command-line? Python not working in the command line of git bash Run function in script from command line (Node JS)