Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c589df4

Browse files
committed
Basic webserver
1 parent 885a407 commit c589df4

File tree

4 files changed

+51
-1
lines changed

4 files changed

+51
-1
lines changed

week1/index.js

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,24 @@
1-
console.log("Hello world")
1+
import HTTP from 'http'
2+
3+
import sendIndexHTML from './responses/sendIndexHTML'
4+
import sendStylesCSS from './responses/sendStylesCSS'
5+
import sendText from './responses/sendText'
6+
7+
const server = HTTP.createServer((request, response) => {
8+
console.log(request.method, request.url)
9+
10+
if (request.url === '/') {
11+
sendIndexHTML(response)
12+
} else if (request.url === '/styles.css') {
13+
sendStylesCSS(response)
14+
} else {
15+
response.statusCode = 404
16+
sendText(response, 'This page cannot be found')
17+
}
18+
19+
response.end()
20+
})
21+
22+
server.listen(3001)
23+
24+
console.log('Server started')

week1/responses/sendIndexHTML.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export default function sendIndexHTML(response) {
2+
response.setHeader('Content-Type', 'text/html')
3+
response.write(`
4+
<!html>
5+
<html>
6+
<head>
7+
<title>Hello</title>
8+
<link href="styles.css" type="text/css" rel="stylesheet"/>
9+
</head>
10+
<body>
11+
Hello I am a website
12+
</body>
13+
</html>
14+
`)
15+
}

week1/responses/sendStylesCSS.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
export default function sendStylesCSS(response) {
2+
response.setHeader('Content-Type', 'text/css')
3+
response.write(`
4+
body {
5+
background: yellow;
6+
}
7+
`)
8+
}

week1/responses/sendText.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export default function sendText(response, text) {
2+
response.setHeader('Content-Type', 'text/plain')
3+
response.write(text)
4+
}

0 commit comments

Comments
 (0)