Topic 21 of 55
CLI Execution
Overview
The Node.js Command Line Interface (CLI) allows you to execute JavaScript files directly from your terminal, evaluate code on the fly, or check syntax without running the script.
Syntax
bash
# Execute a file
node index.js
# Execute a string of code directly (Eval)
node -e "console.log('Hello from CLI')"
# Check syntax without executing (useful for CI/CD)
node -c index.js
# Print the Node.js version
node -vCommon Pitfalls
- Always ensure your `node` executable is in your system's PATH. Use tools like NVM (Node Version Manager) to easily switch between Node.js versions.
- Running `node` without arguments opens the REPL, which is great for testing but won't save your code.
Real-World Example
Using the Node REPL (Read-Eval-Print Loop) for quick debugging:
example
bash
$ node
Welcome to Node.js v20.11.0.
Type ".help" for more information.
> const crypto = require('crypto');
undefined
> crypto.randomUUID()
'5c316715-bf89-40ea-920f-cb9192931557'
> .exit