- Introduction
- Quick-Start
- Server Lifecycle
- Public HTTP API
- Code Reference (Functions & Components)
- Extending the Project
- Troubleshooting & FAQ
This repository contains an ultra-light Node.js application that demonstrates the minimum code required to spin up an HTTP server.
Despite its size, it is production-ready and can be used as a starting point for more complex services.
index.js (13 LOC) ──▶ HTTP server ──▶ "Hello Node!" 🌍
-
Install dependencies (there are none besides Node.js itself) and start the server:
npm install # optional – there are no runtime deps, but keeps lock-file up-to-date npm start # or: node index.js
-
Open your browser or issue a curl request:
curl http://localhost:3000/ # → Hello Node! -
Stop the server with Ctrl + C.
Environment variables:
| Variable | Default | Description |
|---|---|---|
PORT |
3000 |
Port the server listens on. |
The server is started in index.js using Node's built-in http module.
const http = require('http');
const port = process.env.PORT || 3000;
const server = http.createServer(/* request handler */);
server.listen(port, () => console.log(`Server running on http://localhost:${port}/`));There is no additional framework involved. All Node versions ≥ 12.x are supported.
| Method | Path | Query / Body | Response | Example |
|---|---|---|---|---|
GET |
/ |
– | 200 OK – plain-text message Hello Node!\n |
curl http://localhost:3000/ |
curl -i http://localhost:3000/Response:
HTTP/1.1 200 OK
Content-Type: text/plain
Date: <timestamp>
Connection: keep-alive
Content-Length: 11
Hello Node!
const res = await fetch('http://localhost:3000/');
const txt = await res.text(); // → "Hello Node!\n"| Symbol | Location | Description |
|---|---|---|
server |
index.js |
Instance of http.Server returned by http.createServer. |
requestListener(req, res) |
inline in index.js |
Handles all incoming requests. Always responds with status 200 and body Hello Node!\n. |
(req, res) => {
res.statusCode = 200; // set HTTP status
const msg = 'Hello Node!\n';
res.end(msg); // send response & close connection
}req– IncomingMessage object representing the client's request.res– ServerResponse object used to construct the response.
undefined – side-effect: writes to res and terminates the request.
Because the current implementation is framework-less, you can evolve it in multiple ways:
- Add Routes – Inspect
req.urland conditionally handle paths, or switch to a router like Express. - Serve JSON – Change
Content-Typeand respond with serialized data. - Logging – Plug in
morganor another logger for structured logs. - Static Assets – Use
fs.createReadStreamto serve files.
Q: I get EADDRINUSE: port 3000 already in use.
A: Either stop the existing process using that port or run PORT=4000 npm start.
Q: How can I deploy this to the cloud?
A: Because there are virtually no external dependencies, this app runs out-of-the-box on Heroku, Render, AWS Elastic Beanstalk, Fly.io, Railway, etc.
© 2024 Node Hello Contributors