Node.js Lesson 2: Install & Your First Script
Let’s install Node.js and run your first server-side JavaScript file.
Installation
# Go to nodejs.org → Download LTS version
# Verify installation:
node --version # v20.x.x or higher
npm --version # comes with Node
Your First Node.js Script
// hello.js
const message = "Hello from Node.js!";
console.log(message);
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((a, b) => a + b, 0);
console.log("Sum:", sum);
// Run in terminal:
// node hello.js
Node.js vs Browser JavaScript
// Browser JS has:
// document, window, localStorage, fetch (sort of), DOM
// Node.js has:
// process, __filename, __dirname, require(), module
// NO document or window!
console.log(__filename); // full path to this file
console.log(__dirname); // directory containing this file
console.log(process.version); // Node version
console.log(process.platform); // "win32", "darwin", "linux"
REPL — Interactive Node.js
# In terminal, just type:
node
# Now you can type JS directly:
> 2 + 2
4
> "hello".toUpperCase()
"HELLO"
> .exit # to quit
🏋️ Practice Task
Create a file “calculator.js”. Write a function that takes two numbers and an operator (+, -, *, /). Return the result. Test it with console.log. Run it with: node calculator.js
💡 Hint: function calculate(a, op, b) { if (op === “+”) return a + b; … } console.log(calculate(10, “*”, 5));