Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to a script processed by ts-node

Tags:

ts-node

I just started ts-node utilizing. It is the a very convenient tool. Run time looks clear. But it does not work for CLI solutions. I can not pass arguments into a script compiled.

ts-node --preserve-symlinks src/cli.ts -- printer:A

It does not work. I am asking for a help.

like image 998
Victor Shelepen Avatar asked Jan 04 '19 14:01

Victor Shelepen


People also ask

Which object holds all arguments passed after executing a script with the node command?

In Node. js, as in C and many related environments, all command-line arguments received by the shell are given to the process in an array called argv (short for 'argument values'). There you have it - an array containing any arguments you passed in.

What happens if you execute the node command without any arguments?

At the very least, a script that's run without any arguments will still contain two items in the array, the node executable and the script file that is being run.


Video Answer


4 Answers

command

ts-node ./test.ts hello stackoverflow

ts file

console.log("testing: >>", process.argv[2], process.argv[3]);

output

$ testing: >> hello stackoverflow

Happy coding

like image 96
x-magix Avatar answered Oct 17 '22 06:10

x-magix


You did not provide your script, so I can only guess at how you are extracting the arguments. This is how I have made it work with my own test script args.ts:

const a = process.argv[2];
const b = process.argv[3];
const c = process.argv[4];
console.log(`a: '${a}', b: '${b}', c: '${c}'`);

Called from package.json like this:

"scripts": {
   "args": "ts-node ./args.ts -- 4 2 printer:A"
}

This will give me output like this:

a: '4', b: '2', c: 'printer:A'
like image 20
Steve Boyd Avatar answered Oct 17 '22 05:10

Steve Boyd


Try this:

node --preserve-symlinks -r ts-node/register src/cli.ts printer:A
like image 5
Ron Avatar answered Oct 17 '22 04:10

Ron


NODE_OPTIONS

For the case of node options, in addition to -r ts-node/register mentioned at https://stackoverflow.com/a/60162828/895245 they now also mention in the docs the NODE_OPTIONS environment variable: https://typestrong.org/ts-node/docs/configuration/#node-flags

NODE_OPTIONS='--trace-deprecation --abort-on-uncaught-exception' ts-node ./index.ts

A quick test with:

main.ts

(async () => { throw 'asdf' })()

and run:

NODE_OPTIONS='--unhandled-rejections=strict' ts-node main.ts
echo $?

which gives 1 as expected.

Tested on Node v14.16.0, ts-node v10.0.0.