siva
siva

Reputation: 3

Get mounted path of the connected USB drive on insertion Node.js

I am using usb-detection module to detect USB Insert/Eject. But that module doesn't provide any method to get the mounted path. Kindly help me out getting it.

Upvotes: 0

Views: 2379

Answers (1)

Sudhakar Ramasamy
Sudhakar Ramasamy

Reputation: 1759

You can use the drivelist module to get the list of USB drives on usb-detection module's insert/eject event and take the diff. This is a hacky way that I had written a couple of weeks ago. Writing a native node module might be the best way to do it.

const usbDetect = require('usb-detection');
const drivelist = require('drivelist');

let usbList = [];

usbDetect.startMonitoring();

// Detect insert
usbDetect.on('add', () => {
    const poll = setInterval(() => {
        drivelist.list().then((drives) => {
            drives.forEach((drive) => {
                if (drive.isUSB) {
                    const mountPath = drive.mountpoints[0].path;
                    if (!usbList.includes(mountPath)) {
                        console.log(mountPath); //op
                        usbList.push(mountPath);
                        clearInterval(poll)
                    }
                }
            })
        })
    }, 2000)
});


// Detect remove
usbDetect.on('remove', () => {
    let newUsbList = []
    let removalList = []
    drivelist.list().then((drives) => {
        drives.forEach((drive) => {
            if (drive.isUSB) {
                newUsbList.push(drive.mountpoints[0].path);
            }
        })
        removalList = usbList.filter(x => !newUsbList.includes(x));
        usbList = usbList.filter(x => !removalList.includes(x))
        console.log(removalList) // op
    })
});

//usbDetect.stopMonitoring()

Upvotes: 2

Related Questions