Run function in script from command line (Node JS)

2019-01-21 02:55发布

问题:

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?

回答1:

No comment on why you want to do this, or what might be a more standard practice: here is a solution to your question....

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

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

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.



回答2:

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.



回答3:

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

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

You should 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



回答4:

Install run-func to your project

npm i -D run-func

Run any exported function

run-func db.js init

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

run-func db.js init param1 param2

This can also run from "scripts" section in package.json

"db-init": "run-func db.js init"

Important init must be exported in your db.js file

module.exports = { init };

or ES6 export

export { init };


回答5:

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



回答6:

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();


回答7:

Simple, in the javascript file testfile.js:

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

Running at the prompt:

node testfile.js


回答8:

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