Executing JavaScript Files with Node
You'll learn: How to save JavaScript code in a file and run it from your terminal using Node.js.
Now that you've explored the Node.js REPL for quick experiments, it's time to write JavaScript that lives in a file—the way real programs are built.
Creating Your First JavaScript File
Think of a .js file like a recipe card that Node.js reads from top to bottom. Create a new file (you can name it anything, like hello.js) and add some JavaScript:
console.log("Hello from my JavaScript file!");
console.log("Node is running my code!");
Save this file somewhere you can find it (like your Desktop or a projects folder).
Running the File with Node
Open your terminal or command prompt and navigate to the folder where you saved hello.js. Then type:
node hello.js
Hit Enter. Node.js will read your file, execute each line of code in order, and display the output in your terminal.
Analogy: The REPL is like having a conversation—you say something, Node responds immediately. Running a file is like handing Node a script to perform—it reads through the entire thing and executes it all at once.
Why This Matters
Files let you write longer programs, save your work, and organize code logically. Every JavaScript application you'll build—whether a web server, automation script, or tool—starts as code in .js files that Node executes.
Key Takeaway: Save JavaScript code in a .js file and run it with node filename.js from the command line to execute complete programs outside the REPL.