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 tagged with javascript node.js command-line

~ Asked on 2015-06-11 13:48:41

The Best Answer is


No comment on why you want to do this, or what might be a more standard practice: here is a solution to your question.... Keep in mind that the type of quotes required by your command line may vary.

In your db.js, export the init function. There are many ways, but for example:

module.exports.init = function () {

Then call it like this, assuming your db.js is in the same directory as your command prompt:

node -e 'require("./db").init()'

To other readers, the OP's init function could have been called anything, it is not important, it is just the specific name used in the question.

~ Answered on 2016-04-07 15:36:36


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

module.exports.someFunction = function () {

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

~ Answered on 2017-12-24 17:05:30

Most Viewed Questions: