Journal

Raw Notes

  • Today I am playing around with Node.js to play around with Grafana

    • If you are importing your own module in Node.js you have to use a ./ or /
      const http = require('http');		

Node does not require much to spin up a web application server in fact this amount of code is all you really need

//require the HTTP Server
const http = require('http');
 
// Build the server and have it log on sonsole the request coming in
const server = http.createServer((req, res) => {
	console.log(req)
});
 
// Keep the server listening on port 3000 on localhost
server.listen(3000);

I am assuming the more I dive into these tutorials we just grab the request … manipulate or pipe it to the appropriate methods then serve it via res (response).

The Node event loop is a single thread loop.

process.exit();

The above is a hard exit

The below is a really gross way to get an actual response body. It shows how Node.js serves data thought I guess

Request and Response Headers

//require the HTTP Server
const http = require('http'); 
 
// Build the server and have it log on sonsole the request coming in
const server = http.createServer((req, res) => {
 
	// Console log the request URL, the request method, and the request headers
	console.log(req.url, req.method, req.headers)
 
	// Really gross way to inject an HTML response
	// Setting the header tells the client that they are about to recieve HTML
	res.setHeader('Content-Type', 'text/html');
 
	// The write method allows you to append body of the rresponse data
	res.write('<html>');
	res.write('<head><title>Web Page</title></head>');
	res.write('<body><h1>TOOODOOOLOOOO</h1></body>');
	res.write('</html>');
 
	//Informs the client there is no more data from the response. We are done
	res.end();
 
});
 
  
 
// Keep the server listening on port 3000 on localhost
 
server.listen(3000);

Useful link on headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers

Routing Requests

//require the HTTP Server
const http = require('http');
 
// Build the server and have it log on sonsole the request coming in
const server = http.createServer((req, res) => {
 
	// We are now stating that if th client goes to the home page load the HTML in the If Statement
	const url = req.url;
	if (url === '/') {
		res.write('<html>');
		res.write('<head><title>Web Page</title></head>');
		res.write('<body><form action="/message" method="POST"><input type= "text" name="message"><button type="submit">Send</button></form></body>');
		res.write('</html>');
		return res.end()
	}
 
	// Really gross way to inject an HTML response
	// Setting the header tells the client that they are about to recieve HTML
	res.setHeader('Content-Type', 'text/html');
 
	// The write method allows you to append body of the rresponse data
	res.write('<html>');
	res.write('<head><title>Web Page</title></head>');
	res.write('<body><h1>TOOODOOOLOOOO</h1></body>');
	res.write('</html>');
 
//Informs the client there is no more data from the response. We are done
	res.end();
 
});
 
  
 
// Keep the server listening on port 3000 on localhost
 
server.listen(3000);

The above basically is a dirty way for routing

Redirecting request

//NEW Raw logic gross
 
if (url === '/message' && method === 'POST') {
	const body = [];
	//look into request.on more and what Data and end do
	req.on('data', (chunk) => {
		console.log(chunk);
		body.push(chunk);
	});
 
	// When the request is over this listener will now be triggered
	req.on('end', () => {
		const parseBody = Buffer.concat(body).toString();
		const message = parseBody.split('=')[1];
		fs.writeFileSync('message.txt', message);
		res.statusCode = 302;
		res.setHeader('location', '/');
		return res.end();
	});
}

todo look into request.on more and what Data and end do. I am not 100% sure how this all stacks up to Nodes event loop

Blocking and non Blocking code

Blocking

	req.on('end', () => {
		const parseBody = Buffer.concat(body).toString();
		const message = parseBody.split('=')[1];
		fs.writeFileSync('message.txt', message); //This is blocking
		res.statusCode = 302;
		res.setHeader('location', '/');
		return res.end();
	});

Non-blocking

	req.on('end', () => {
		const parseBody = Buffer.concat(body).toString();
		const message = parseBody.split('=')[1];
		fs.writeFile('message.txt', message, err => {
			res.statusCode = 302;
			res.setHeader('location', '/');
			return res.end();	
		});
	});

since we want the rest of the code to execute anyways it does not matter but if we had code after writeFile then it would execute? Need more confidence in that

Things to know about Node.js

  1. Uses a single Javascript thread
    1. How does it handle multiple requests if it runs on one thread?
      1. Performance
        1. Working with files takes a long time usually. because of this requests after could be blocked. the event loop sends non quick running code to the worker pool that can use multiple thread detached from the event loop. Once the worker is done though it will trigger the callback
        2. todo Learn about the event loop and worker pool
        3. Event Loop
          1. Checks for timer callbacks like setTimeout and setInterval
          2. Checks pending callbacks like Execute, I/O related operations, callbacks that were differed.
          3. Poll Phase. Retrieve new I/O events and execute callbacks
          4. Check Phase. kinda zoned out here
          5. Close Callbacks. if you have close events then it would execute them
          6. I checked out. This is stuff I will dive into if I ever care how Node.js actually runs