-
Notifications
You must be signed in to change notification settings - Fork 2
/
prettierd.js
72 lines (70 loc) · 1.67 KB
/
prettierd.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
#!/usr/bin/env node
const net = require('net');
const argv = process.argv.slice(1);
const port = 9870;
if (argv.includes('-c')) {
// client
const stdin = process.stdin;
const stdout = process.stdout;
const stderr = process.stderr;
const file = argv.indexOf('-f');
if (file === -1 || !argv[file + 1]) {
stderr.write("missing filename\n");
process.exit(1);
return;
}
const con = net.createConnection({ port }, () => {
// send filename
con.write(argv[file + 1]);
con.write("\n");
// send stdin to server
stdin.pipe(con, { end: true });
con.on('data', msg => {
stdout.write(msg, 'utf8')
});
});
con.on('error', err => {
stderr.write(err.message);
process.exit(1);
});
return;
}
// server
const prettier = require("prettier");
const options = { allowHalfOpen: true };
const server = net.createServer(options, con => {
let fileName = '';
let seenName = false;
let fileData = '';
con.on('data', msg => {
const input = msg.toString('utf8');
if (seenName) {
fileData += input;
return;
}
const lineFeed = input.indexOf("\n");
if (lineFeed > -1) {
const before = input.substr(0, lineFeed);
const after = input.substr(lineFeed + 1);
fileName += before;
fileData += after;
seenName = true;
return;
}
fileName += input;
});
con.on('end', () => {
const config = prettier.resolveConfig.sync(fileName);
const result = prettier.format(fileData, config);
con.write(result);
con.destroy();
})
});
server.on('error', err => {
console.error(err.message);
});
process.on('SIGINT', () => {
server.close();
process.exit();
});
server.listen(port);