简体   繁体   中英

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)

Ie, the function is not invoked.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM