Running JS files
You save code in a .js file and give it to the node command to run it.
In this page:
Syntax
node file.js
node file.js arg1 arg2 // read with process.argv
Running JS files
Run a file with node file.js. Command-line arguments are available in process.argv, where the first two entries are the node path and the script path. The exit code is set with process.exit(code) or process.exitCode.
Note:
Use process.argv.slice(2) to get only your own arguments.
Example: Running JS files
const args = process.argv.slice(2);
console.log("Script args:", args);
console.log("Args length:", args.length);
console.log("Is main module:", require.main === module);
console.log("File name ends with app.js:", __filename.endsWith("app.js"));
// Output:
// Script args: []
// Args length: 0
// Is main module: true
// File name ends with app.js: true
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting the .js file path relative to the current directory
- Reading argv[0] expecting the first argument
- Calling process.exit before async work finishes
Chapter Summary
- node file.js runs a script
- process.argv holds arguments
- slice(2) gives user arguments
- process.exitCode sets the exit status
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: