如何检测使用Node.js连接的USB设备
问题描述:
我是Node.js的新手。我想检测是否有任何USB /大容量存储设备连接到系统。如何检测使用Node.js连接的USB设备
因为我们有东西在C#中做这样
// 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();
请建议我们如何做类似的C#东西Node.js的
答
Node-usb是一个节点库,我认为它提供了你正在寻找的确切的东西。我不确定如何在没有库的情况下做到这一点,但是如果您不想使用外部库,也许可以检查它们的源代码。
根据他们的文档,你可以使用
var usb = require('usb')
usb.on('attach', function(device) { ... });
一个新的设备连接时运行的回调。
答
即使是一个更好的解决方案是使用 'USB-检测' https://www.npmjs.com/package/usb-detection
可以,按ProductID或VENDORID收听特定的USB设备过滤:
// 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); });
如何安装 'NPM安装USB-检测' ..我的系统是Windows 7的64位,不能安装...错误检测..plz帮助我 –
正如他们的github上所述的命令是“npm install usb”,但它也说; Windows:使用Zadig为您的USB设备安装WinUSB驱动程序。否则,您尝试打开设备时会得到LIBUSB_ERROR_NOT_SUPPORTED。 – Robin