How to Detect USB device connected using Node.js
Solution 1
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); });
Solution 2
Node-usb is a node library which I think provides the exact thing you are looking for. I am unsure how to do it without the library, but perhaps you can check their source code if you don't want to use an external library.
According to their documentation you can use
var usb = require('usb')
usb.on('attach', function(device) { ... });
to run a callback when a new device is connected.
Aboobakkar P S
I like providing simple solutions to perplexing puzzles to people. Pretty much excited about the javascript frameworks. When I am free, I read. Origami is life. Also, pen down my thoughts in aboopallikara
Updated on August 20, 2020Comments
-
Aboobakkar P S over 3 years
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.