Skip to content

Instantly share code, notes, and snippets.

@Kyngo
Created January 3, 2023 12:32
Show Gist options
  • Save Kyngo/d761b4273d794f4b74b7d0b2aea95e7e to your computer and use it in GitHub Desktop.
Save Kyngo/d761b4273d794f4b74b7d0b2aea95e7e to your computer and use it in GitHub Desktop.
Bare-bones HTTP server in Node.js - No 'http' or 'express' used
const net = require('net');
const fs = require('fs');
const os = require('os');
const path = require('path');
const process = require('process');
const PORT = 8888;
const LOGS_PATH = path.join(os.tmpdir(), 'server.log');
const server = net.createServer((socket) => {
socket.on('data', (data) => {
const _ = parseRequest(data.toString());
const response = createResponse('Hello, World!');
socket.write(response);
});
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT} - logs stored under ${LOGS_PATH}`);
});
function logRequest(data) {
const log = `${(new Date()).toUTCString()} - ${data.method} ${data.path}`;
fs.access(process.cwd(), fs.constants.W_OK, function(err) {
if (err) {
console.error("[W] Cannot write logs in current path!");
} else {
if (!fs.existsSync(LOGS_PATH)) {
fs.writeFileSync(LOGS_PATH, '');
}
fs.appendFileSync(LOGS_PATH, log + '\n');
for (const idx in data) {
fs.appendFileSync(LOGS_PATH, `${idx}: ${data[idx]}\n`);
}
fs.appendFileSync(LOGS_PATH, '\n');
}
});
console.log('[I]', log)
}
function parseRequest(data) {
const splitData = data.split(/[\r\n]/g).filter((idx) => idx.length > 0);
const firstLine = splitData[0].split(/\s/g);
const queryPath = firstLine[1].split('?', 2);
const res = {
method: firstLine[0],
path: queryPath[0],
query: queryPath[1] ||''
}
splitData.shift();
for (const idx in splitData) {
const dataLine = splitData[idx].split(/\:\s/);
res[`${dataLine[0]}`] = dataLine[1];
}
logRequest(res);
return res;
}
function createResponse(body) {
return `HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: ${body.length}
${body}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment