Node.js用于列出所有USB存储设备的脚本

时间:2015-09-22 12:42:26

标签: node.js usb libusb usb-drive

我想写一个node.js脚本。

它会在控制台上显示一条消息,比如说:

USB CONNECTED: usb-name, usb-manufacturer-name

例如:

$ node.js listubs.js
USB CONNECTED: New Volume, ADATA

到目前为止,我只能检测到连接的usb设备是usb-storage是Linux cmd行“usb-devices”。但我不知道usb存储的用户友好名称。

如何知道用户友好名称?

我读过usb-detection,usb npm模块,但我找不到我需要的东西。 我还想让脚本能够挂载和卸载usb-storage。

1 个答案:

答案 0 :(得分:0)

您可能会发现drivelist有帮助。它是一个列出计算机中所有已连接驱动器的模块,可移动或不可移动(标有system布尔属性)。这是Linux系统的示例输出:

[
    {
        device: '/dev/sda',
        description: 'WDC WD10JPVX-75J',
        size: '931.5G',
        mountpoint: '/',
        system: true
    },
    {
        device: '/dev/sdb',
        description: 'DataTraveler 2.0',
        size: '7.3G',
        mountpoint: '/media/UNTITLED',
        name: '/dev/sdb',
        system: false
    }
]

您可以按照system: false来获取可删除列表的列表。

关于检测驱动器是否已连接,您可以在一个间隔内调用drivelist,并将新结果与旧结果进行比较以确定是否有任何添加。您可以重用the following code在两个drivelist输出::

之间执行diff操作
_ = require('lodash')

containsDeep = (array, item) ->
    return _.any(_.map(array, _.partial(_.isEqual, item)))

differenceDeep = (x, y) ->
    return _.filter(x, _.partial(_.negate(containsDeep), y))

createDiffOperation = (type, element) ->
    return {
        type: type
        drive: element
    }

var drivelistDiff = (previous, current) ->
    additions = differenceDeep(current, previous)
    removals = differenceDeep(previous, current)

    mappingAdditions = _.map(additions, _.partial(createDiffOperation, 'add'))
    mappingRemovals = _.map(removals, _.partial(createDiffOperation, 'remove'))

    return {
        drives: current
        diff: _.union(mappingAdditions, mappingRemovals)
    }