Run function in script from command line (Node JS)

2019-01-21 02:42发布

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?

8条回答
不美不萌又怎样
2楼-- · 2019-01-21 03:47

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 };
查看更多
Fickle 薄情
3楼-- · 2019-01-21 03:47

Simple, in the javascript file testfile.js:

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

Running at the prompt:

node testfile.js
查看更多
登录 后发表回答