[英]How to Detect USB device connected using Node.js
我是Node.js的新手。 我想檢測是否有任何USB / Mass存儲設備連接到系統。
因為我們在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();
請建議我們如何在Node.js中執行類似C#的操作。
Node-usb是一個節點庫,我認為它提供了您正在尋找的確切內容。 我不確定如何在沒有庫的情況下執行此操作,但如果您不想使用外部庫,也許可以檢查其源代碼。
根據他們的文檔,你可以使用
var usb = require('usb')
usb.on('attach', function(device) { ... });
連接新設備時運行回調。
更好的解決方案是使用'usb-detection'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); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.