Day 1 - 100DaysOfCopilot - Simple Node Server

Day 1 - 100DaysOfCopilot - Simple Node Server

Published
Published July 25, 2022
Author
Omar Nava
Today I start with this challenge: #100DaysOfCopilot.
 
So to start with, I decided to code a very very simple Node.JS server, with no libraries, just a straightforward example. NodeJS is known territory for me so I wanted to start with this example in order to know when Github Copilot (GC) was going in a totally wrong direction. It took like 5 minutes to create this project.
 
In the beginning, I started writing some comments to guide GC into what is what I intended for this code. If you give it the chance, it’ll give a lot of suggestions on what to achieve with the code. In the end, it never suggested to me the code for what it initially suggested to me in the comments to do in this app. This is my first try so I need to master which kind of comments are the most useful for creating code with GC.
 
Here is the code for this 1st day:
 
// Create a node server that listens on port 3000. const http = require('node:http'); const hostname = '127.0.0.1'; // create server const server = http.createServer((req, res) => { // return response for index page if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/html' }); // return response with health status res.end('<h1>Health Status: OK</h1>'); } // return response for /api else if (req.url === '/api') { res.writeHead(200, { 'Content-Type': 'application/json' }); // return success response for /api res.end(JSON.stringify({ message: 'Success' })); } // return response for /api/users else if (req.url === '/api/users') { // return user's array as response const users = [ { name: 'John', age: 20 }, { name: 'Jane', age: 21 }, { name: 'Bob', age: 22 }, ]; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(users)); } }); server.listen(3000, hostname, () => { console.log(`Server running at http://${hostname}:3000/`); });
 
 
Remember that the code shown in this article might have errors and shouldn’t be used for production.