Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call specific NodeJS function in package.json scripts

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.

like image 745
CaribouCode Avatar asked Jan 07 '16 11:01

CaribouCode


1 Answers

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.

like image 182
Alexander K Avatar answered Oct 14 '22 05:10

Alexander K