Simple HTTP Server in Node.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');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation:
-
Import the
http
module: This module provides tools for creating and managing HTTP servers. - Define hostname and port: These define where the server will listen for connections.
-
Create a server: The
http.createServer()
function creates a new server instance. -
Define request handler: The function passed to
createServer()
handles incoming requests. It receives thereq
(request) andres
(response) objects. -
Set response headers:
res.statusCode
sets the status code of the response (200 for success), andres.setHeader()
adds custom headers. -
Send response body:
res.end()
sends the response body and ends the connection. -
Start the server:
server.listen()
starts the server and logs a message when it's ready.
To run this code:
- Save it as
server.js
. - Open your terminal and navigate to the directory where you saved the file.
- Run
node server.js
. - Open your web browser and visit
http://127.0.0.1:3000/
. You should see "Hello World" displayed.
Other Node.js Examples
1. Read a file:
const fs = require('fs');
fs.readFile('myfile.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
2. Create a directory:
const fs = require('fs');
fs.mkdir('new_directory', { recursive: true }, (err) => {
if (err) {
console.error(err);
return;
}
console.log('Directory created successfully!');
});
3. Use a module from npm:
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
These are just simple examples. Node.js offers a vast ecosystem of modules and libraries for various tasks, including web development, data processing, and more. You can explore the documentation at https://nodejs.org/ to learn more.
Top comments (0)