【问题标题】:How to Detect USB device connected using Node.js如何检测使用 Node.js 连接的 USB 设备
【发布时间】:2019-08-20 13:29:21
【问题描述】:

我是 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();

请建议我们如何在 Node.js 中做类似 C# 的事情。

【问题讨论】:

    标签: javascript node.js meteor serial-port


    【解决方案1】:

    更好的解决方案是使用“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); });
    

    【讨论】:

      【解决方案2】:

      Node-usb 是一个节点库,我认为它提供了您正在寻找的确切内容。我不确定如何在没有库的情况下执行此操作,但如果您不想使用外部库,也许可以查看他们的源代码。

      根据他们的文档,您可以使用

      var usb = require('usb')
      usb.on('attach', function(device) { ... });
      

      在连接新设备时运行回调。

      【讨论】:

      • 如何安装'npm install usb-detection'..我的系统是windows 7 64位,无法安装...检测到错误..请帮助我
      • 正如他们的 github 上所说,命令是“npm install usb”,但它也说; Windows:使用 Zadig 为您的 USB 设备安装 WinUSB 驱动程序。否则你会在尝试打开设备时得到 LIBUSB_ERROR_NOT_SUPPORTED。
      • 我很抱歉添加问题应该在哪里回复。我没有完全理解图书馆。如何从设备读取数据(在我的情况下是条码扫描仪)?
      猜你喜欢
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2013-11-10
      • 1970-01-01
      相关资源
      最近更新 更多