-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.js
88 lines (72 loc) · 2.26 KB
/
client.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
let nssocket = require('nssocket')
let fs = require('fs')
let path = require('path')
let rimraf = require('rimraf')
let mkdirp = require('mkdirp')
let argv = require('yargs').argv
// augment songbird
require('songbird')
let dirName = argv.dir || path.join(process.cwd(), 'client-files')
// const TCP_HOST = '127.0.0.1'
const TCP_PORT = 6785
const ROOT_DIR = path.resolve(dirName)
const TCP_EVENT_MAP = {
'create': 'SERVER-CREATE',
'update': 'SERVER-UPDATE',
'remove' : 'SERVER-DELETE',
'ack': 'CLIENT-ACK'
}
let tcpClient = new nssocket.NsSocket({
reconnect: true
})
// Sync PUT request
tcpClient.data([TCP_EVENT_MAP.create], (payload) =>{
writeDataToFile(payload).catch(e => console.log);
})
// Sync POST request
tcpClient.data([TCP_EVENT_MAP.update], (payload) => {
writeDataToFile(payload).catch(e => console.log);
})
// SYNC DELETE request
tcpClient.data([TCP_EVENT_MAP.remove], (payload) => {
async () => {
logSocketReq(payload);
let filePath = path.resolve(path.join(ROOT_DIR, payload.path))
if(payload.type === 'dir'){
await rimraf.promise(filePath)
} else await fs.promise.unlink(filePath)
sendSuccessAck(payload.action)
}().catch(e => console.log)
})
tcpClient.connect(TCP_PORT);
function getDirPath(filePath, type) {
let endsWithSlash = filePath.charAt(filePath.length-1) === path.sep
let hasExt = path.extname(filePath) !== ''
let isDir = type === 'dir' ? true : false
let dirPath = isDir ? filePath : path.dirname(filePath)
return dirPath;
}
function logSocketReq(payload) {
console.log(payload);
}
function sendSuccessAck(actionType) {
// send a message back to server
tcpClient.send([TCP_EVENT_MAP.ack], {'message': `${actionType} action success`})
}
async function writeDataToFile (payload) {
logSocketReq(payload);
let filePath = path.resolve(path.join(ROOT_DIR, payload.path))
if(payload.action === 'create') {
let dirPath = getDirPath(filePath, payload.type)
// create the directory path first
await mkdirp.promise(dirPath)
} else if(payload.action === 'update') {
// turncate existing file
await fs.promise.truncate(filePath, 0)
}
if(payload.type === 'file') {
//write payload.contents to that filePath
await fs.promise.writeFile(filePath, payload.contents, {encoding: 'base64'});
}
sendSuccessAck(payload.action)
}