[Node] Basic

Creating a Node Server

Core modules:

  • http: launch a server, send request
  • https: launch a SSL encrypted server
  • fs: file system
  • path: constructing apths
  • os
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// app.js
const http = require('http');

function rqListener(req, res) {
// receive two arguments: request, response
// Will run for every request that reaches the server
}
http.createServer(rqListener); // Execute rqListener function for every incoming request.

// OR use anonymous function
const server = http.createServer((req, res) => {
// process.exit() could kill the event loop of node
})

server.listen(3000); // Let nodejs listen to port 3000

Sending response

1
2
3
4
5
6
7
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<p>Helllo</p>');
res.write('/<html>');
res.end();
})

Routing Request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

const fs = require('fs');

const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;

if (url === '/') {
res.write('<html>');
res.write('<head><title>Enter Message</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();
}

if (url === '/messasge' && method === 'POST') {
const body = []
req.on('data', chunk => {
// receives a chunk of data
body.push(chunk);
});
req.on('end', () => {
// when all chunks are precessed
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
fs.writeFile('message.txt', message, (err) => {
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
});
})
}
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<head><title>My First Page</title></head>);
res.write('<body><h1>Hello from my Node.js Server!</h1></body>');
res.write('</html>');
res.end();
});

server.listen(3000);