Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
216 lines (183 loc) · 7.04 KB
/
Copy pathapp.js
File metadata and controls
216 lines (183 loc) · 7.04 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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var formidable = require('formidable');
var fs = require('fs');
var http = require('http');
var JSZip = require('jszip');
var Docxtemplater = require('docxtemplater');
var winston = require('winston');
var Sentry = require('winston-raven-sentry');
var Raven = require('raven');
var expressions = require('angular-expressions');
// Must configure Raven before doing anything else with it
Raven.config(process.env.SENTRY_DSN).install();
winston.emitErrs = true;
var logger = new winston.Logger({
transports: [
new winston.transports.File({
level: 'info',
filename: './logfile.log',
handleExceptions: true,
json: false,
colorize: false,
timestamp: function () {
return new Date().toLocaleString('es');
}
}),
new winston.transports.Console({
level: 'info',
handleExceptions: true,
json: false,
colorize: true
}),
new Sentry({
level: 'error',
dsn: process.env.SENTRY_DSN
})
],
exitOnError: false
});
// Expression needed to be able to write {clientame | lower}
expressions.filters.lower = function(input) {
// This condition should be used to make sure that if your input is undefined, your output will be undefined as well and will not throw an error
if(!input) return input;
return input.toLowerCase();
};
expressions.filters.upper = function(input) {
// This condition should be used to make sure that if your input is undefined, your output will be undefined as well and will not throw an error
if(!input) return input;
return input.toUpperCase();
};
var angularParser = function(tag) {
return {
get: tag === '.' ? function(s){ return s;} : function(s) {
return expressions.compile(tag.replace(/(’|“|”)/g, "'"))(s);
}
};
};
// Instance express
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// The request handler must be the first middleware on the app
app.use(Raven.requestHandler());
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/* GET home page. */
app.get('/', function (req, res, next) {
res.render('index', {title: 'Docx parser tester'});
});
/* POST upload file */
app.post('/', function (req, res, next) {
var form = new formidable.IncomingForm();
// Callback to answer inconming POST request
form.parse(req, function (err, fields, files) {
// Error detected: pass to next route handler
if (err) next(err);
var context;
var uploaded_path;
// Get file
try {
uploaded_path = files.file.path;
} catch (typeError) {
logger.error('empty file');
res.status(400);
return res.json({'success': false, 'reason': 'empty file'})
}
// Get context
try {
context = JSON.parse(fields.context);
}
catch (parseError) {
var e = {
message: parseError.message,
name: parseError.name,
stack: parseError.stack,
properties: parseError.properties
};
logger.error(JSON.stringify({parseError: e}));
// The error contains additional information when logged with JSON.stringify (it contains a property object).
res.status(400);
return res.json({'success': false, 'reason': 'invalid context data: ' + e.message});
}
// Read file sent
fs.readFile(uploaded_path, function (err, data) {
if (err) {
logger.error('error reading input file: ' + err.message);
res.status(500);
return res.json({'success': false, 'reason': 'error reading input file'})
}
var zip;
var doc;
var buf;
// Load uploaded file and set the template variables
try {
zip = new JSZip(data);
doc = new Docxtemplater();
doc.loadZip(zip).setOptions({parser: angularParser});
doc.setData(context);
} catch (e) {
logger.error('error loading input file: ' + e.message);
res.status(500);
return res.json({'success': false, 'reason': 'error loading input file'})
}
try {
// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
doc.render()
}
catch (error) {
var e = {
message: error.message,
name: error.name,
stack: error.stack,
properties: error.properties
};
logger.error(JSON.stringify({error: e}));
// The error contains additional information when logged with JSON.stringify (it contains a property object).
res.status(500);
return res.json({'success': false, 'reason': 'error replacing vars'});
}
// generate output data
try {
buf = doc.getZip().generate({type: 'nodebuffer'});
// buf is a nodejs buffer, you can either write it to a file or do anything else with it.
fs.writeFileSync(path.resolve(path.join(process.cwd(), '/uploads/'), 'output.docx'), buf);
} catch (err) {
logger.error('error generating output file: ' + err.message);
res.status(500);
return res.json({'success': false, 'reason': 'error generating output file'});
}
// Send output docx file
res.setHeader('Content-Disposition', 'attachment; filename=docx_file_replaced.docx');
res.setHeader('Content-Transfer-Encoding', 'binary');
res.setHeader('Content-Type', ' application/vnd.openxmlformats-officedocument.wordprocessingml.document');
res.status(200);
res.write(buf, 'binary');
res.end(null, 'binary');
});
});
});
// The error handler must be before any other error middleware
app.use(Raven.errorHandler());
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// The error id is attached to `res.sentry` to be returned
// and optionally displayed to the user for support.
res.statusCode = 500;
res.end(res.sentry + '\n');
});
module.exports = app;