-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhttpSocketGet.js
More file actions
52 lines (46 loc) · 1.3 KB
/
httpSocketGet.js
File metadata and controls
52 lines (46 loc) · 1.3 KB
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
52
const { Socket } = require('net');
const collectHeadersAndContent = (result, line) => {
if (line === '') {
result.content = '';
return result;
}
if ('content' in result) {
result.content += line;
return result;
}
const [key, value] = line.split(': ');
result.headers[key] = value;
return result;
};
const readHeader = (text) => {
const [response, ...headersAndContent] = text.split('\r\n');
const { headers, content } = headersAndContent.reduce(collectHeadersAndContent, { headers: {} });
return { response, headers, content };
}
const main = (host, port, resource) => {
const request = [
`GET ${resource} HTTP/1.0`,
`Host: ${host}`,
`User-Agent: Mozilla/5.0`,
`Accept: */*`,
'',
''
].join('\n');
const client = new Socket();
client.setEncoding('utf8');
client.on('connect', () => client.write(request));
client.once('data', (text) => {
let { response, headers, content } = readHeader(text);
console.warn(response);
console.warn(headers);
client.on('data', (chunk) => content += chunk);
client.on('end', () => {
console.log(content);
console.warn('disconnected')
});
});
client.connect({ host, port });
}
//python3 -m http.server to start a local server
//'localhost', 8000, '/'
main(...process.argv.slice(2))