Skip to content

Instantly share code, notes, and snippets.

@rajivnarayana
Created May 11, 2021 10:59
Show Gist options
  • Save rajivnarayana/245374c22100d955e0f49cc561cb7445 to your computer and use it in GitHub Desktop.
Save rajivnarayana/245374c22100d955e0f49cc561cb7445 to your computer and use it in GitHub Desktop.
NodeJS - Create a server from core modules.

Objective

Create a bare bones server using nodejs core modules and not expressjs.

Which core modules are used

  1. http
  2. url

Concepts

Create a server from http

const { Server } = require("http");
const app = new Server((req, res) => {
  res.writeHead(404);
  res.write("Cannot find "+req.url);
  res.end();
});

Use some mechanism to handle requests based on the req.url inside the server handler.

const { Server } = require("http");
const url = require('url');
function extractQueryParams(p) {
const u = url.parse(p, true);
return u.query;
}
const app = new Server((req, res) => {
if (req.url.startsWith("/")) {
const params = extractQueryParams(req.url);
if (!params.name) {
res.writeHead(200);
res.write("Hello Anonymous!");
res.end();
} else {
res.writeHead(200);
res.write("Hello "+ params.name +"!");
res.end();
}
} else {
res.writeHead(404);
res.write("Cannot get "+req.url);
res.end();
}
});
app.listen(4200, () => {
console.log(`Server started on port 4200`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment