I have some code that parses a pcap file and writes the parsed data into an array data = [] and then writes that data to a JSON file:
var fs = require("fs");
var pcapp = require('pcap-parser');
var hex = "";
var data = [];
var i = 0;
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
var parser = pcapp.parse('C:/Users/Brandt Winkler Prins/Desktop/data.pcap');
parser.on('packet', function(packet) {
hex = [...packet.data].map(_ => ('0' +_.toString(16)).slice(-2)).join();
var ticker = hex2a(hex.substring(282, 306).replace(/,/g,""));
var bidPrice = parseInt(hex.substring(318,342).split(",").reverse().join(""), 16);
var timestamp = parseInt(hex.substring(258, 282).split(",").reverse().join(""), 16);
if(packet.header.capturedLength == 126 && ticker == "AAPL ") {
data[2*i] = bidPrice;
data[2*i-1] = timestamp;
i++
}
});
data = JSON.stringify(data);
fs.writeFile("C:/Users/Brandt Winkler Prins/Desktop/Project/data.json",data);
All of the data gets written to its respective array in parser.on(...) however node.js executes my .writeFile command before it executes parser.on(...). In sum, my question is this: how can I force node to execute my code before writing my file?
Any help is greatly appreciated.