-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch-gopher.js
70 lines (46 loc) · 1.14 KB
/
fetch-gopher.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const { URL } = require('url');
const net = require('net');
const gopherSubMenu = require('gopher-protocol').gopherSubMenu;
module.exports = async uri => {
const urlObj = new URL(uri);
const client = new net.Socket();
let resourceType;
let path;
if (urlObj.pathname==='/') {
// root
resourceType = '1';
path = '';
} else {
resourceType = urlObj.pathname.substring(1, 1);
path = urlObj.pathname.substring(2);
}
const port = urlObj.port || 70;
console.log('host:', urlObj.host);
console.log('port:', port);
client.connect(urlObj.port || 70, urlObj.host, () => {
console.log('path:', path);
client.write(path + "\r\n");
});
let resp = '';
client.on('data', data => {
resp+=data;
});
return new Promise( (res, rej) => {
client.on('error', err => {
rej(err);
});
client.on('close', () => {
switch(resourceType) {
case '1':
res([resourceType, parseMenu(resp)]);
break;
case 0:
res([resourceType, resp]);
break;
}
});
});
};
const parseMenu = input => {
return gopherSubMenu.parse(input);
};