How to Run JavaScript in Terminal Using Node.js
To run JavaScript in the terminal using
node, open your terminal and type node followed by your JavaScript file name, like node filename.js. You can also run JavaScript interactively by just typing node and entering code line by line.Syntax
To run a JavaScript file with Node.js, use the command:
node filename.js: Runs the JavaScript file namedfilename.js.node: Starts an interactive JavaScript shell where you can type and run code line by line.
bash
node filename.js
Example
This example shows how to create a simple JavaScript file and run it using Node.js in the terminal.
javascript
console.log('Hello from Node.js!');
Output
Hello from Node.js!
Common Pitfalls
Common mistakes when running JavaScript with Node.js include:
- Not saving the JavaScript file before running it.
- Running
nodewithout a file and expecting it to run a script automatically. - Using browser-specific JavaScript features that Node.js does not support.
Always save your file and run it explicitly with node filename.js.
bash
Wrong: node script Right: node script.js
Quick Reference
| Command | Description |
|---|---|
| node filename.js | Run JavaScript file named filename.js |
| node | Start interactive Node.js shell |
| Ctrl + C | Exit interactive shell or stop running script |
Key Takeaways
Use
node filename.js to run JavaScript files in the terminal.Type
node alone to open an interactive JavaScript shell.Save your JavaScript file before running it with Node.js.
Node.js does not support browser-only JavaScript features.
Use Ctrl + C to exit the interactive shell or stop scripts.