Javascript Webserver

Overview

Creating and hosting a webserver is fairly easy. The script provided on this page is a sample implementation of a webserver written purely in Javascript. The only requirement is that your machie must be able to run standalone (not in the browser) Javascript. This can be accomplished by installing Node.js.

Javascript Server

const http = require('node:http'); const url = require('node:url'); const hostname = '127.0.0.1'; const port = 3000; // Create the web server const server = http.createServer((req, res) => { // Parse the URL to get the path (e.g., '/about' or '/contact') const parsedUrl = url.parse(req.url, true); const path = parsedUrl.pathname; // Set the response header to JSON format res.setHeader('Content-Type', 'application/json'); // Route handling logic (Registering paths) if (path === '/' || path === '/home') { res.statusCode = 200; res.end(JSON.stringify({ message: 'Welcome to the Home Page!' })); } else if (path === '/api/user') { res.statusCode = 200; res.end(JSON.stringify({ id: 1, name: 'Alex', role: 'Developer' })); } else if (path === '/about') { res.statusCode = 200; res.end(JSON.stringify({ message: 'This is the About Page.' })); } else { // 404 Not Found fallback if the path doesn't match anything above res.statusCode = 404; res.end(JSON.stringify({ error: 'Route not found' })); } }); // Start the server server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });