4

A javascript file foo.js has the following content:

function foo(param){
    console.log('foo called with params');
    console.log(param);
}
module.exports.foo = foo;

How can I call this function from within a package.json script?

"scripts": {
        "foo": "node foo.js foo(1)", 
    },

Just returns

node foo.js foo(1)

I.e., the function is not invoked.

Oblomov
  • 8,953
  • 22
  • 60
  • 106

1 Answers1

3

Your command node foo.js foo(1) does not run even if you don't put it inside an npm script:

  • Don't wrap your code inside a function if you wish to execute it from the command line
  • use process.argv[2] to capture args from the command

Which means that your foo.js script should look like:

console.log('generateI18 is with param');
console.log(process.argv[2]);

(no need to export anything)

And you can execute it as:

node foo.js 1

You can then add it to your npm scripts:

"scripts": {
    "foo": "node foo.js 1", 
},

and run it:

npm run foo
klugjo
  • 19,422
  • 8
  • 57
  • 75