← Back to Node.js Course | Chapter 1: Introduction | Lesson 6 of 7

Running JS files

You save code in a .js file and give it to the node command to run it.

In this page:

  1. Running JS files
Syntax
javascript
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

javascript
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
  1. Forgetting the .js file path relative to the current directory
  2. Reading argv[0] expecting the first argument
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.