2

In a npm project I want to call a custom function with arguments, or better, provide it as a script in the package.json in a manner like: npm run custom-function "Hello, World".

At the moment I have a a file src/myFunction.ts:

import * as extLib from 'libFromNodeModules'; // we need npm to resolve this dependency

export const runFunction = function (arg: string) {
  console.log(extLib.process(arg));
};

The closest thing I've managed to call this function is:

{
  ...
  scripts: {
        "custom-function": "ts-node -e 'require(\"./src/myFunction.ts\").runFunction()'",
  }
  ...
}

This does a tad more than just ts-node src/myFunction.ts, but still doesn't allow me to pass arguments and is probably not the right approach anyway. How do I have to set this up correctly?

NotX
  • 1,516
  • 1
  • 14
  • 28
  • Like this? https://stackoverflow.com/questions/11580961/sending-command-line-arguments-to-npm-script – danh Mar 17 '21 at 15:18
  • @danh In that case I would need to know how the `script.js` there looks like that it accepts arguments when called in that manner. ;) – NotX Mar 17 '21 at 15:27

1 Answers1

1

To run foo.js, passing "bar"...

"scripts": {
  "custom": "node foo.js bar"
}

npm run custom

process.argv is set to the command line...

// foo.js
console.log(process.argv) // prints ['path/node', 'path/foo.js', 'bar']
danh
  • 62,181
  • 10
  • 95
  • 136