Node.js Get Started
In this lesson you install Node.js and run your first programs.
Installing Node.js
- Go to the official Node.js website
- Download the LTS version for your system
- Run the installer and keep the default options (npm is installed with it)
On Linux and macOS, many developers use a version manager such as nvm, which lets you switch between Node.js versions.
Open a terminal and check that it worked:
Example
node -v
npm -vv24.11.0 11.6.1
Running Your First File
Create a folder node-practice, open it in VS Code, and create app.js:
Example
const shop = "Ayesha's Bakery";
const cakes = 12;
const pricePerCake = 1500;
console.log("Shop:", shop);
console.log("Cakes in stock:", cakes);
console.log("Stock value: Rs", cakes * pricePerCake);Run it from the terminal in the same folder:
Example
node app.jsShop: Ayesha's Bakery Cakes in stock: 12 Stock value: Rs 18000
The REPL
Type node alone to open the REPL (Read, Evaluate, Print, Loop). You can try JavaScript one line at a time:
Example
nodeExample
> 25 * 4
100
> "karachi".toUpperCase()
'KARACHI'
> .exitUse .exit or press Ctrl + C twice to leave.
Useful Global Values
Some values are available in every Node.js file without importing anything:
| Name | What it gives you |
|---|---|
console | Printing: console.log, console.error, console.table |
process | Information about the running program |
process.argv | Command-line arguments |
process.env | Environment variables, like secret keys |
__dirname | The folder of the current file (CommonJS only) |
setTimeout, setInterval | Timers |
Command-Line Arguments
process.argv is an array. The first two items are the path to Node.js and the path to your file; your own arguments come after them.
Example
// greet.js
const name = process.argv[2] || "friend";
const city = process.argv[3] || "Pakistan";
console.log(`Hello ${name} from ${city}!`);Example
node greet.js Bilal KarachiHello Bilal from Karachi!
Environment Variables
Keep passwords and API keys out of your code. Read them from environment variables instead:
Example
const port = process.env.PORT || 3000;
console.log("Server will use port", port);Recent Node.js versions can load a .env file for you:
Example
node --env-file=.env app.jsNever upload your .env file to GitHub. Add it to .gitignore.
Auto-Restart with --watch
While you are learning, it is useful to rerun the file every time you save:
Example
node --watch app.jsNode.js now restarts the program each time you save a change. Press Ctrl + C to stop. Older projects use a package called nodemon for the same job.
Exiting a Program
A Node.js program ends when there is nothing more to do. A server keeps running because it waits for requests. You can end a program yourself with process.exit():
Example
if (!process.env.API_KEY) {
console.error("API_KEY is missing");
process.exit(1);
}Exit code 0 means success; any other number means an error.
Exercise
Exercise
Which command runs a file called server.js with Node.js?
