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?
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
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
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 () {
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.
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