Last Sync: 2022-09-12 19:30:04

This commit is contained in:
tactonbishop 2022-09-12 19:30:04 +01:00
parent 4a390f037a
commit 24ad25e20c
2 changed files with 11 additions and 13 deletions

View file

@ -2,7 +2,6 @@
categories: categories:
- Programming Languages - Programming Languages
tags: tags:
- Programming_Languages
- backend - backend
- node-js - node-js
- node-modules - node-modules
@ -19,28 +18,28 @@ An HTTP server is another instance of an [event emitter](/Programming_Languages/
_Creating a server_ _Creating a server_
```js ```js
const http = require('http'); const http = require("http");
const server = http.createServer(); // Create server as emitter const server = http.createServer(); // Create server as emitter
// Register functions to run when listener is triggered // Register functions to run when listener is triggered
server.on('connection', (socket) => { server.on("connection", (socket) => {
console.log('new connection...'); console.log("new connection...");
}); });
server.listen(3000); server.listen(3000);
console.log('Listening on port 3000'); console.log("Listening on port 3000");
``` ```
This server is functionally equivalent to a generic event emitter: This server is functionally equivalent to a generic event emitter:
```js ```js
// Raise an event // Raise an event
const emitter = new EventEmitter('messageLogged'); const emitter = new EventEmitter("messageLogged");
// Register a listener // Register a listener
emitter.on('messagedLogged', function () { emitter.on("messagedLogged", function () {
console.log('The listener was called.'); console.log("The listener was called.");
}); });
``` ```
@ -54,8 +53,8 @@ A socket is a generic protocol for client-server communication. Crucially it **a
```js ```js
const server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
if (req.url === '/') { if (req.url === "/") {
res.write('hello'); res.write("hello");
res.end(); res.end();
} }
}); });
@ -67,8 +66,8 @@ Below is an example of using this architecture to return JSON to the client:
```js ```js
const server = http.createServer((req, res) => { const server = http.createServer((req, res) => {
if (req.url === '/products') { if (req.url === "/products") {
res.write(JSON.stringify(['shoes', 'lipstick', 'cups'])); res.write(JSON.stringify(["shoes", "lipstick", "cups"]));
res.end(); res.end();
} }
}); });

View file

@ -2,7 +2,6 @@
categories: categories:
- Programming Languages - Programming Languages
tags: tags:
- Programming_Languages
- shell - shell
--- ---