To understand how to work Node.js web application, this is the simple example, the title is “dice-game-program”.
It is very simple but I think it works to understand the basic of Node.js web application development.
How web applications work?
Web servers work by accepting connections from multiple web clients (web browsers) connecting to internet. The accesses between web servers and web clients complete based on HTTP.
HTTP connection is “state less” so that when web browsers access to web servers web servers simply send response to web browsers.
Which means web servers do not find if who accesses or where the users came from.
So the internet shopping sites and SNSs need Cookie to identify who is connecting to their sites.
Node.js sample program : Displaying different contents based on accessing URLs
The ‘dice-game’ program displays different contents based on accessing URLs. Each time you access to the URL random numbers will be shown.
- When you access to URL of ‘/dice/6’ , Hexahedral dice will be emulated
- If you access to URL of ‘/dice/12’, Dodecahedron dice will be emulated.
Actual code of dice-program
Here is the actual JS codes with some explanation.
// Load http modules const http = require('http') const ctype = { 'Content-Type': 'text/html;charset=utf-8'} // Start web server const svr = http.createServer(handler) // Generating server svr.listen(8081) // Listing on port 8081 // When accessed to server function handler (req, res) { consturl=req.url // Judgement of URL // Is the URL top page? if (url=='/'||url=='index.html') { showIndexPage(req, res) return } // If the URL dice page? if (url.substr(0, 6) =='/dice/') { showDicePage(req, res) return } // Other pages res.writeHead(404, ctype) res.end('4004 not found') } // When dice program's index page has been acceessed function showIndexPage (req, res) { // Generating HTTP header res.writeHead(200, ctype) // Contents of response output consthtml='<h1>Dice Index Page</h1>\n'+ '<p><a href="/dice/6">Hexahedral dice</a></p>'+ '<p><a href="/dice/12">Dodecahedron dice</a></p>' res.end(html) } //When Dice Index Page gets access function showDicePage (req, res) { // http header output res.writeHead(200, ctype) // Which dice is needed? 6 or 12? consta=req.url.split('/') constnum=parseInt(a[2]) // Generating random numbers constrnd=Math.floor(Math.random() *num) +1 // Contents of response output res.end('<p style="font-size:72px;">'+rnd+'</p>') }
After the learning
This sample program worked to understand basic for me. So that I hope it will work for you as well!