Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Detect USB device connected using Node.js

I am newbie to Node.js. I would like to detect if any USB / Mass storage device is connected to the system.

As we have something in C# to do like

// Add USB plugged event watching
        watcherAttach = new ManagementEventWatcher();
        watcherAttach.EventArrived += watcherAttach_EventArrived;
        watcherAttach.Query = new WqlEventQuery("SELECT * FROM  Win32_DeviceChangeEvent WHERE EventType = 2");
        watcherAttach.Start();

        // Add USB unplugged event watching
        watcherDetach = new ManagementEventWatcher();
        watcherDetach.EventArrived += watcherDetach_EventArrived;
        watcherDetach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
        watcherDetach.Start();

Please suggest how we can do something similar of C# in Node.js.

like image 476
Aboobakkar P S Avatar asked Mar 07 '16 12:03

Aboobakkar P S


1 Answers

Even a better solution is to use 'usb-detection' https://www.npmjs.com/package/usb-detection

You can listen to specific usb devices filtering by productId or vendorId:

// Detect add or remove (change) 
usbDetect.on('change', function(device) { console.log('change', device); });
usbDetect.on('change:vid', function(device) { console.log('change', device); });
usbDetect.on('change:vid:pid', function(device) { console.log('change', device); });

// Get a list of USB devices on your system, optionally filtered by `vid` or `pid` 
usbDetect.find(function(err, devices) { console.log('find', devices, err); });
usbDetect.find(vid, function(err, devices) { console.log('find', devices, err); });
usbDetect.find(vid, pid, function(err, devices) { console.log('find', devices, err); });
// Promise version of `find`: 
usbDetect.find().then(function(devices) { console.log(devices); }).catch(function(err) { console.log(err); });
like image 165
javimaravillas Avatar answered Sep 20 '22 03:09

javimaravillas