I'm having a lot of trouble wrapping my head around the asynchronous nature of code execution on NodeJS. I have a simple function to fetch the output of ip a
on a Linux machine and parse out the IP Subnet manually. I'd simply like to console.log()
the IP Subnet after that's done.
I understand that NodeJS mostly runs asynchronously so I can't expect the logic to be finished before I console.log()
the variable. I understand to concept of Callbacks to combat this problem, but I'd prefer to have access to the variable outside the logic loop. I turned to Promises, which seems like a good solution for this, but I think I'm missing something and they're not working the way I expected. Here's my code below:
let subnetString = '';
function getIPLinux() {
return new Promise((resolve) => {
const ipOutput = spawn( 'ip', ['a'] );
ipOutput.stdout.on('data', (data) => {
String(data).split('\n').forEach( (line) => {
if ( line.includes('inet') && line.indexOf('inet6') < 0 && line.indexOf('127.0.0.1') < 0 ) {
const ipSubnet = line.split(' ')[5];
const ipStringArray = ipSubnet.split('.');
subnetString = ipStringArray[0] + '.' + ipStringArray[1] + '.' + ipStringArray[2] + '.*';
console.log('Found subnet at end of if loop: ' + subnetString);
}
})
})
console.log('Found subnet at end of promise: ' + subnetString);
resolve();
})
}
getIPLinux().then( () => {
console.log('Found subnet after then: ' + subnetString);
});
My output is as follows:
Found subnet at end of promise:
Found subnet after then:
Found subnet at end of if loop: 192.168.1.*
Only the last line logged is correct. I'm having trouble wrapping my mind around this non-blocking code execution. I'm open to other methodologies too if I'm coming at this the wrong way.