I have the following problem, I have an xml to json converter in javascript and this converter saves the converted object to a variable. I need to adapt this code to enable writing the file from the nodejs, but so far I have not been able to solve the problem. Converter code:
function XMLtoJSON() {
var me = this; //
me.fromFile = function(xml, rstr) {
var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
// sets and sends the request for calling "xml"
xhttp.open("GET", xml, false);
xhttp.send(null);
// gets the JSON string
var json_str = jsontoStr(setJsonObj(xhttp.responseXML));
return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
}
me.fromStr = function(xml, rstr) {
if (window.DOMParser) {
var getxml = new DOMParser();
var xmlDoc = getxml.parseFromString(xml, "text/xml");
} else {
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
}
var json_str = jsontoStr(setJsonObj(xmlDoc));
return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
}
var setJsonObj = function(xml) {
var js_obj = {};
if (xml.nodeType == 1) {
if (xml.attributes.length > 0) {
js_obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
js_obj["@attributes"][attribute.nodeName] = attribute.value;
}
}
} else if (xml.nodeType == 3) {
js_obj = xml.nodeValue;
}
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(js_obj[nodeName]) == "undefined") {
js_obj[nodeName] = setJsonObj(item);
if (nodeName == "child") {
//js_obj[nodeName] = setJsonObj(item);
js_obj[nodeName] = [];
js_obj[nodeName].push(old);
js_obj[nodeName].push(setJsonObj(item));
}
} else {
if (typeof(js_obj[nodeName].push) == "undefined") {
var old = js_obj[nodeName];
js_obj[nodeName] = [];
js_obj[nodeName].push(old);
}
js_obj[nodeName].push(setJsonObj(item));
}
}
}
return js_obj;
}
var jsontoStr = function(js_obj) {
var rejsn = JSON.stringify(js_obj, undefined, 2).replace(/(\t|\r|\n)/g, '').replace(/"",[\n\t\r\s]+""[,]*/g, '').replace(/(\n[\t\s\r]*\n)/g, '').replace(/[\s\t]{2,}""[,]{0,1}/g, '').replace(/"[\s\t]{1,}"[,]{0,1}/g, '').replace(/\[[\t\s]*\]/g, '""').replace(/null,/g, '').replace(/[\]/g, ' - ');
return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn : 'Invalid XML format';
}
};
var xml2json = new XMLtoJSON();
I have tried to add the following code inside that js:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
But I still have not succeeded.
The first line informs me that 'require' is not defined.
Does anyone have any light for this case?
I want to create an html with a button and in the click of the button it will generate the file.