On this page
Setup and First App
Installing Node.js
- Download the LTS version from https://nodejs.org/
- Run the installer for your OS
- Verify installation:
node --version # e.g. v20.x.x
npm --version # e.g. 10.x.x
Version Management (Optional)
Use nvm (Node Version Manager) to switch between Node versions:
# Install nvm (see https://github.com/nvm-sh/nvm)
nvm install 20
nvm use 20
Project Structure
my-api/
├── package.json
├── index.js
├── src/
│ └── routes/
└── node_modules/ (auto-generated)
Initialize a Project
mkdir my-api && cd my-api
npm init -y
This creates package.json:
{
"name": "my-api",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js"
}
}
Your First HTTP Server
Create index.js:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
message: 'Hello from Node.js API!',
path: req.url,
method: req.method
}));
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Run:
node index.js
# or
npm start
Test with curl or browser:
curl http://localhost:3000/users
ES Modules in Node.js
Add to package.json:
{
"type": "module"
}
Then use import/export:
import http from 'http';
const server = http.createServer((req, res) => {
res.end('Hello ES Modules!');
});
server.listen(3000);
Development Tips
- Use
node --watch index.js(Node 18+) for auto-restart on file changes - Install nodemon for older Node versions:
npm install -D nodemon - Use VS Code with the Node.js extension for debugging