Some months ago I got tired of all those tiny differences that you need to consider when writing CLI scripts for node.
So in the last days I took the time to rewrite a module that I have already copied into more than three repositories:
Run module export as a
(See Why not ... for alternative approaches.)
When to use
So you have some code that you want to be able to run from the command line
You can of course just write it down into a file and run it with
Maybe you go one more step and add a hashbang and make it executable
so on a linux shell you run it with just
But this way you can not import the file without executing all the code.
Wrapping all the code into a function and executing it
if (require.main === module) helps with that.
You also manage to parse those arguments you need, maybe using one of the available libraries.
- Are you able to also call your function from code with those arguments?
- Do you need to make any async call (like…
The first version has already been published to npm:
So if your module exports a method named
run it can now be used as a CLI tool:
npx runex path/to/file.js
I still have some ideas for features to implement, but I'm very happy it's out there now.
Merry X-Mas and Let me know what you think