-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
51 lines (44 loc) · 1.7 KB
/
server.js
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
42
43
44
45
46
47
48
49
50
51
import http from 'http';
import fs from 'fs/promises';
const makeServer = (usersById) => http.createServer((request, response) => {
request.on('end', () => {
if (request.url === '/') {
const messages = [
'Welcome to The Phonebook',
`Records count: ${Object.keys(usersById).length}`,
];
response.end(messages.join('\n'));
} else if (request.url.startsWith('/search')) {
// BEGIN (write your solution here)
const queryParams = new URLSearchParams(request.url.split('?')[1] || '')
const searchString = queryParams.get('q');
const regex = new RegExp(searchString, 'i'); // 'i' flag for case-insensitive search
const responseLines = Object.entries(usersById)
.filter(([_, entry]) => regex.test(entry.name)) // Keep only entries where the name matches the regex
.map(([_, entry]) => `${entry.name}, ${entry.phone}`);
let responseStr = responseLines.join('\n');
response.write(responseStr)
response.end()
// END
}
});
request.resume();
});
const startServer = async (port, callback = () => {}) => {
const data = await fs.readFile('phonebook.txt', 'utf-8');
// BEGIN (write your solution here)
const lines = data.trim().split('\n');
const phoneBook = {};
const usersById = lines.reduce((acc, line) => {
const parsedLine = line.split('|').map((word) => word.trim());
acc[parsedLine[0]] = { name: parsedLine[1], phone: parsedLine[2] };
return acc;
}, phoneBook);
// END
const server = makeServer(usersById);
server.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
callback(server);
});
};
startServer(8080)