To run a specific function within a Node.js script directly from the command line, follow these steps:
Structure Your Script: Export the function from your Node.js file. For example:
// myScript.js
function myFunction() {
console.log("Function executed!");
}
module.exports = myFunction;
Use Node's require and Execute: From the command line, invoke the script and the desired function like this:
node -e "require('./myScript')()"
Here, the -e flag allows you to execute a one-liner where the require statement loads the script, and the function is invoked directly.
This method is useful when you want to avoid modifying the script or adding specific command-line argument parsing logic.