-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.js
76 lines (67 loc) · 2.58 KB
/
convert.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
//Usage: node convert {xmlfilename} {xslfilename} {outputtype}
var defaultPort = 9758; //It's XSLT on your phone dial pad.
var libxslt = require('libxslt'),
fs = require('fs'),
path = require('path'),
http = require('http'),
open = require('open'),
libxmljs = libxslt.libxmljs;
//Collect the arguments passed in on the command line.
var xmlFile = process.argv[2],
xslFile = process.argv[3],
outputFile = process.argv[4],
xmlString, xslString;
//Grab the output type from the file extension.
var outputType = outputFile.split(".")[1].toUpperCase();
//Load the XML file.
fs.readFile(__dirname+'/'+xmlFile, function (e,d){
if (e) {
throw e;
}
console.log('[XML]: ' + xmlFile + ' loaded...');
xmlString = d.toString();
//Load the XSL file.
fs.readFile(__dirname+'/'+xslFile, function(e,s){
if (e) {
throw e;
}
console.log('[XSL]: ' + xslFile + ' loaded...');
xslString = s.toString();
convert(xmlString, xslString);
});
});
function convert(xml, xsl){
libxslt.parse(xsl, function(err, stylesheet){
if(err){
throw err;
}
var params = {
//MyParam: 'my value'
};
// 'params' parameter is optional
stylesheet.apply(xml, params, function(err, result){
// err contains any error from parsing the document or applying the stylesheet
// result is a string containing the result of the transformation
if(err){
throw err;
}
if(outputType === 'html' || outputType === 'htm' || typeof(outputType==='undefined')) {
//Fire up a web server so they can see their newly-minted HTML file.
http.createServer(function(req, res) {
res.writeHead(200,{"Content-Type": "text/html"});
res.write(result, encoding='utf8');
res.end();
}).listen(defaultPort);
open('http://localhost:'+defaultPort); //Open a browser window so the user can see their converted file.
fs.writeFile(__dirname + "/output/" + outputFile, result, function(err){
if (err) {
return console.log(err);
}
console.log('[Output]: ' + outputFile + ' written to output directory.');
console.log('Node server running on port ' + defaultPort);
console.log('Ctrl/Cmd+C to end.');
});
}
});
});
}