I have a NodeJS file with an export function a bit like this:
test.js
exports.run = function(){
console.log('You run this function!');
};
Is there a way to specifically call the function from this file using a custom command in the scripts
object of package.json
?
For example, I imagine it would look something like this:
{
"author": "Joe Bloggs",
"name": "test-app",
"main": "server.js",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "NODE_ENV=production node test.js run()",
},
"dependencies": {
"express": "~4.10.6",
}
}
Obviously this is the incorrect syntax to run the function.
You could use a good ol' switch case and pass arguments to your script.
test.js
function foo(){
console.log('foo is called');
}
function bar(){
console.log('bar is called');
}
for (var i=0; i<process.argv.length;i++) {
switch (process.argv[i]) {
case 'foo':
foo();
break;
case 'bar':
bar();
break;
}
}
module.exports.foo = foo;
module.exports.bar = bar;
package.json
{
"author": "A person",
"name": "test-app",
"main": "server.js",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "NODE_ENV=production node test.js foo bar"
},
"dependencies": {
"express": "~4.10.6"
}
}
test.js:foo() and test.js:bar() will now be called by npm test. You can also require it like you normally would.
This answers your question, but your later comments made me unsure if this is what you're after.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With