Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a javascript function with parameters from within a package.json script

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.

like image 323
user1934212 Avatar asked Oct 26 '25 19:10

user1934212


1 Answers

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
like image 161
klugjo Avatar answered Oct 29 '25 08:10

klugjo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!