Run function in script from command line (Node JS)
Here's a quick way to run a function from the command line using Node.js. You can map command line arguments to functions in your script:
Dynamic Imports & Simple Setups
Dynamically Import and Run Functions
Node.js dynamic imports offer a powerful way of flexibly invoking functions right from the command line:
This assumes that your module file names and the exportable function names are identical.
Local > Global
While installing run-func
globally is a possibility, opting for a local installation is ahead in the race. Makes your environment easy to replicate and keeps a clean global namespace intact.
Exporting & Calling
Make Functions Available
Export your functions the accessible way:
This paves the way for modular code that can be executed from anywhere in your application or directly from the command line.
The Caller Function
To ensure your functions are executive-class citizens and callable directly from the command line:
Custom Scripts & Packages
Leverage npm Scripts
Define an npm
script in your package.json
. Maximizes code reuse and prevents carpal syndrome:
Script Execution Safety Checks
To enable a function for both imported and direct CLI usage, put a guard condition:
Was this article helpful?