Expose result of method in Javascript

Viewed 34

I have this method :

// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
    var KLVdata = KLV.parseKLVfile(file, options);
    var packets = KLVdata.packets;
    var nDropped = KLVdata.nDropped;
   
});

in a small Node app.

How to I get the variable packets outside this object?

2 Answers

It's actually quite simple. Define the variables outside the function, and set them inside. Like this:

// Define variables
var packets = null;
var nDropped = null;

// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
    var KLVdata = KLV.parseKLVfile(file, options);
    packets = KLVdata.packets;
    nDropped = KLVdata.nDropped;
   
});

function doSomething(){
    // you can now use the variables anywhere
}

Also: make sure to only use the variables if they have been defined.

// Define variables
var packets = null;
var nDropped = null;

// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
    var KLVdata = KLV.parseKLVfile(file, options);
    packets = KLVdata.packets;
    nDropped = KLVdata.nDropped;
    packetsReady(); // your callback function
});

function packetsReady(){
    // should only be called once the packets are ready
    processPackets(packets);
}

Simply pass it to a function

let packets;
let nDropped;

function processKLV(KLVdata){
    packets = KLVdata.packets;
    nDropped = KLVdata.nDropped;
}

// Parse a whole file
fs.readFile("klv-file.klv", (err, file) => {
     processKLV(KLV.parseKLVfile(file, options));
});
Related