1 |
|
2 |
|
3 | "use strict";
|
4 |
|
5 | var Promise = require("bluebird");
|
6 | var fs = Promise.promisifyAll(require("fs"));
|
7 | var xml2js = require("xml2js");
|
8 | var traverse = require('traverse');
|
9 |
|
10 |
|
11 | var XML2JS_OPTS = {
|
12 | trim: true,
|
13 | normalizeTags: true,
|
14 | normalize: true,
|
15 | mergeAttrs: true
|
16 | };
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | module.exports.parse = function(opt, callback) {
|
24 | if (!opt) {
|
25 | throw new Error("You must provide options: opt.filePath and any other option of " +
|
26 | "https://github.com/Leonidas-from-XIV/node-xml2js#options");
|
27 | }
|
28 | if (!opt.xmlContent && !opt.filePath) {
|
29 | throw new Error("You must provide the opt.filePath or the opt.xmlContent");
|
30 | }
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | if (!opt.xmlContent) {
|
36 | fs.readFileAsync(opt.filePath, "utf8").then(function(xmlContent) {
|
37 | return xmlContent;
|
38 |
|
39 | }).then(_parseWithXml2js).then(function(result) {
|
40 | callback(null, result);
|
41 |
|
42 | }).catch(function(e) {
|
43 | callback(e, null);
|
44 |
|
45 | }).error(function (e) {
|
46 | callback(e, null);
|
47 | });
|
48 |
|
49 | } else {
|
50 |
|
51 | _parseWithXml2js(opt.xmlContent).then(function(result) {
|
52 | delete result.xmlContent;
|
53 | callback(null, result);
|
54 |
|
55 | }).error(function (e) {
|
56 | callback(e);
|
57 | });
|
58 | }
|
59 |
|
60 | };
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | function _parseWithXml2js(xmlContent) {
|
69 | return new Promise(function(resolve, reject) {
|
70 |
|
71 | xml2js.parseString(xmlContent, XML2JS_OPTS, function(err, pomObject) {
|
72 | if (err) {
|
73 |
|
74 | reject(err);
|
75 | }
|
76 |
|
77 |
|
78 | removeSingleArrays(pomObject);
|
79 |
|
80 |
|
81 | resolve({
|
82 | pomXml: xmlContent,
|
83 | pomObject: pomObject
|
84 | });
|
85 | });
|
86 | });
|
87 | }
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | function removeSingleArrays(obj) {
|
94 |
|
95 | traverse(obj).forEach(function traversing(value) {
|
96 |
|
97 | if (value instanceof Array && value.length === 1) {
|
98 | this.update(value[0]);
|
99 | }
|
100 | });
|
101 | }
|