Explain Codes LogoExplain Codes Logo

Run function in script from command line (Node JS)

javascript
dynamic-imports
command-line-arguments
node-js-scripts
Nikita BarsukovbyNikita Barsukov·Mar 5, 2025
TLDR

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:

function myFunction() { console.log('Fun fact: JavaScript and Java are as much the same as car and carpet.'); // Just a programmer's humor } const ARG_FUNCTION_MAP = { '--run': myFunction }; const arg = process.argv[2]; // Second argument ARG_FUNCTION_MAP[arg]?.(); // Usage: node script.js --run

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:

const functionName = process.argv[2]; import(`./${functionName}.js`).then(module => { module[functionName](); }); // Usage: node script.js functionName

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.

"scripts": { "run-function": "run-func db.js" }
npm run run-function init

Exporting & Calling

Make Functions Available

Export your functions the accessible way:

// db.js module.exports = { init }; // You can also go the ES6 way export const init = () => { // your logic here };

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:

if (require.main === module) { // An idiom to ensure the script is not being imported const [,,func, ...args] = process.argv; if (typeof module.exports[func] === 'function') { module.exports[func](...args); // Call the big shot function } } // Usage: node db.js init arg1 arg2 arg3 ...

Custom Scripts & Packages

Leverage npm Scripts

Define an npm script in your package.json. Maximizes code reuse and prevents carpal syndrome:

"scripts": { "init-db": "node -e \"require('./db.js').init()\"" }
npm run init-db // The DB init marathon

Script Execution Safety Checks

To enable a function for both imported and direct CLI usage, put a guard condition:

// Make init() serves the coffee only when db.js is the head chef. if (require.main === module) { init(); }