Search code examples
javascriptnode.jssearchcommand-linedevice-discovery

How can I execute command line arguments in a node.js script


Im pretty new to programming and im trying to make efforts - probably this question is not really worth to be asked but I am not making any progress since.. way too long.

I am trying to do a discovery search on all devices that are connected to my local network in a node.js script.

I found this npm module which should do the job: https://www.npmjs.com/package/local-devices/v/3.0.0

So I just tried to copy-paste the example they have given to search my network for all devices:

const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})

But if I run the script now, nothing happens.

What i've tried so far: 1. I tried to save the output in a constant and tried to output this on a console

const found = find().then(devices => {
    devices 
    /*[
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    return devices
  })
  console.log(found);

then the console output is Promise { <pending> }. I couldnt figure out what to do with this yet.

  1. there is this command line argument arp -a which, if executed in the command line, lists all ip adresses of all devices in the network in the terminal. So it basically does exactly what I want, but I need to work with that output in the following code (I need to find one specific ip adress of a smart plug from this list, but that is a different story).

How can I take this command line argument, and execute it in my javascript code/ my node.js script, and save the output in a variable/const?

Best regards, Michael


Solution

  • Certainly worth asking! JS can be a confusing language to learn.

    If a function returns a Promise (as find does) then logging what it returns is not normally very useful. A Promise is something which will at some point be able to potentially give some sort of useful value.

    The .then part of your function is where you can use the value that the promise contains. A Promise will run the function contained in .then once it has got the value back. So doing something like:

    const find = require('local-devices');
    
    // Find all local network devices.
    find().then(devices => {
      console.log(devices);
    })
    

    Means that when the function which finds the devices has got a value back, it will log that value.