Ahmed Shendy
Ahmed Shendy

Reputation: 1711

Node.js Script for listing all usb storage devices

I would like to write a node.js script.

It will display a message on the console, let's say:

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

ex:

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

Ihe only place till now that help me detect that the connected usb device is a usb-storage is the Linux cmd line "usb-devices". But I can't know the user friendly name of the usb storage.

How to know the user friendly name ?

I read about usb-detection, usb npm module, but I can't find what I need from them. I would like also to make the script be able to mount and umount the usb-storage.

Upvotes: 1

Views: 5937

Answers (1)

jviotti
jviotti

Reputation: 18949

You might find drivelist helpful. Its a module to list all connected drives in your computer, either removable or not (marked with a system boolean property). This is an example output from a Linux system:

[
    {
        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
    }
]

You can filter the list by the ones that have system: false to get the removable ones.

Regarding detecting if a drive was connected, you can call drivelist in an interval, and compare the new result with the old one to determine any additions. You can re-use the following code that performs a diff operation between two drivelist outputs::

_ = 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)
    }

Upvotes: 3

Related Questions