As your first Node.js app, you'll build a web server that replies with Hello World whenever the browser sends a request. This lesson is where the Node.js backend mindset really begins—a request comes in, and the server sends back a response.
// File: app.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('Hello World from Node.js\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});require('http') pulls in Node.js's built-in HTTP module. The function inside http.createServer() runs every time a request comes in. res.end() is where the response gets sent back to the browser/client.
Server running at http://127.0.0.1:3000/ Browser result: Hello World from Node.jsInfo
Don't close the terminal while the server is running—closing it will stop the server. After you change the code, stop the server with Ctrl + C and run it again.