Creating HTTP server using Node js
const http = require('http'); // Import the HTTP module
// Create a server object
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' }); // Set response header
res.end('Hello, World!\n'); // Send response and end the request
});
// Start the server and listen on port 3000
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
File system
// Importing the http and fs module
const http = require("http")
const fs = require("fs")
// Creating server
const server = http.createServer((req, res) => {
const log = ${Date.now()}: new req received\n;
fs.appendFile("log.txt",log,(err,data) => {
res.end("hello from server agin");
});
});
// Server listening to port 3008
server.listen((3008), () => {
console.log("Server is Running");
})
Reading and Writing to a File
This program reads the content of a file and writes a new file with modified content.
const fs = require('fs'); // Import the File System module
// Read the content of 'input.txt'
fs.readFile('input.txt', 'utf-8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
console.log('File content:', data);
// Write the content to 'output.txt' with additional text
const newData = `${data}\nThis is the appended text.`;
fs.writeFile('output.txt', newData, (err) => {
if (err) {
console.error('Error writing file:', err);
} else {
console.log('File has been written to output.txt');
});
});
Program 3: Basic Express Server with Routing
This program uses Express to set up a server with multiple routes.
const express = require('express'); // Import Express module
const app = express(); // Create an Express application
const PORT = 3000; // Define the port
// Home route
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
// About route
app.get('/about', (req, res) => {
res.send('This is the About Page.');
});
// Contact route
app.get('/contact', (req, res) => {
res.send('This is the Contact Page.');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
URL Module Example
var url = require('url');
var http = require('http');
http.createServer((req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
//Return the url part of the request object:
res.write(req.url);
res.end();
}).listen(3000);
Example of Express Application
const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;
// Serve static files from the 'public' folder
app.use(express.static(path.join(__dirname, 'public')));
// Route for the homepage
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});