I'm really a noob in JavaScript and I'm trying to write a small ElectronJS/NodeJS app. I think the purpose of the App is not relevant to the question, suffice it to say that the App will listen to TCP connections that will send ~100MB of XML content and then will do some further processing on the parsed XML. Since the XML content is "large" the parsing is taking some time to process, so I decided to put the parsing in an asynchronous function but the code is apparently running synchronously. I'm not sure if I'm doing something wrong or if it's just because of the single-thread (AFAIU) nature of JavaScript.
var net = require('net');
const fs = require('fs');
const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser");
const parser = new XMLParser();
var file_counter = 0;
var server = net.createServer(function(connection) {
console.log('Client Connected');
var content = "";
connection.on('data', function(data) {
content += data.toString();
});
connection.on('end', async function() {
console.log("client " + file_counter + " disconnected");
saveObj(content, file_counter);
console.log("returned from " + file_counter);
file_counter++;
});
connection.write('y');
});
async function saveObj(data, cnt) {
return new Promise(res => setTimeout(() => {
let jObj = parser.parse(data);
console.log("Parsed content number " + cnt);
}, 1000));
}
The output that I get consistently is Parsed content number 0, 1, 2...N.
Even though the size of "data" is quite different from one connection to another.
Comments
Post a Comment