Reputation: 806
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.
Upvotes: 6
Views: 29051
Reputation: 275
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); });
Upvotes: 8
Reputation: 1261
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.
Upvotes: 6