-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
90 lines (77 loc) · 1.98 KB
/
app.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
89
90
const http = require('http');
const fs = require('fs');
const spawn = require('child_process').spawn;
var crypto = require('crypto');
var argv = require('optimist')
.default('p', 8080)
.argv;
var wordExeList = [
'C:\\Program Files\\Microsoft Office\\Office15\\WINWORD.EXE',
'C:\\Program Files (x86)\\Microsoft Office\\Office15\\WINWORD.EXE'
];
var wordExec = null;
if (argv.w) {
if (fs.existsSync(argv.w)) {
wordExec = argv.w;
}
} else {
for (var key in wordExeList) {
if (fs.existsSync(wordExeList[key])) {
wordExec = wordExeList[key];
break;
}
}
}
if (wordExec != null) {
createServer(argv.p);
} else {
console.error("Word executable not found");
}
function createServer(port) {
var server = http.createServer(handleRequest);
server.listen(port, function() {
console.log("Server listening on: http://localhost:%s", argv.p);
});
}
function handleRequest(request, response) {
var docBinary = '';
request.setEncoding('binary')
request.on('data', function(chunk) {
docBinary += chunk;
});
request.on('end', function() {
crypto.randomBytes(10, function(ex, buf) {
var name = buf.toString('hex');
fs.writeFile(name + ".docx", docBinary, 'binary', function(err) {
if (err) {
return returnError(response, err);
}
onSavedInput(response, name);
});
});
});
}
function onSavedInput(response, name) {
const converter = spawn(wordExec, ['/mExportToPDFext', '/q', name + ".docx"]);
converter.on('close', function(code) {
if (code !== 0) {
return returnError(response);
}
fs.readFile(name + '.pdf', function(err, data) {
if (err) {
return returnError(response, err);
}
response.end(data);
cleanFiles(name);
});
});
}
function returnError(response, err) {
response.statusCode = 500;
response.end('An error occured');
return console.log(err);
}
function cleanFiles(name) {
fs.unlink(name + ".pdf");
fs.unlink(name + ".docx");
}