我正在为用户制作一个将数据传输到USB的功能,我正在使用“USB”包。
如果我这样做
const devices = getDeviceList();
,然后我通过USB连接所有设备信息,如鼠标和键盘。但是,我应该只指定USB大容量存储。在这种情况下,我如何指定它?欢迎任何建议,并提前表示感谢!
仅供参考:我试着具体说明,但
console.log("usb device is: ", usbDevice);
给我
null
这是我的代码:
import {usb, getDeviceList} from "usb";
import fs from "fs";
import path from "path";
async function path2usb(selectedMeasures) {
// Assuming selectedMeasures is an array of data to be exported
try {
usb.on("attach", function (device) {
console.log("USB device attached:");
console.log(device);
});
usb.on("detach", function (device) {
console.log("USB device detached:");
console.log(device);
});
// Get a list of USB devices
const devices = getDeviceList();
console.log("devices are: ", devices);
// Find the first USB mass storage device (e.g., a USB stick)
let usbDevice = null;
for (const device of devices) {
const descriptor = device.deviceDescriptor;
if (
descriptor &&
descriptor.bDeviceClass === 0x08 && // USB mass storage class
descriptor.bDeviceSubClass === 0x06 && // USB mass storage subclass
(descriptor.bDeviceProtocol === 0x50 || descriptor.bDeviceProtocol === 0x01) // Bulk-only transport or SCSI transparent command set
) {
usbDevice = device;
break; // Stop iterating once the USB stick is found
}
}
console.log("usb device is: ", usbDevice);
if (usbDevice) {
usbDevice.open();
const usbInterface = usbDevice.interface(0);
usbInterface.claim();
const endpoint = usbInterface.endpoint(0x81); // Assuming the endpoint is 0x81, you may need to check the endpoint address for your specific USB device.
if (endpoint) {
const folderName = selectedMeasures.join("_"); // Combine the selected measures to form the folder name
const targetFolderPath = path.join("/data", folderName); // Create the target folder path in the 'data' directory
// Check if the folder exists
if (!fs.existsSync(targetFolderPath)) {
throw new Error("Folder not found in 'data' directory.");
}
const targetFilePath = path.join(
`/dev/${endpoint.deviceDescriptor.iSerialNumber}`,
`${folderName}.txt`
); // Create the target file path in the USB mass storage device
// Write the exported data to the file
fs.writeFileSync(targetFilePath, selectedMeasures.join("\n"));
console.log(`Data exported to USB-drive: ${targetFilePath}`);
return targetFilePath;
} else {
// If the endpoint is not found, throw an error
throw new Error("USB endpoint not found!");
}
} else {
// If no USB mass storage device is found, throw an error
throw new Error("No USB Mass Storage device found!");
}
} catch (error) {
console.error("Error exporting data to USB drive:", error.message);
throw error;
}
}
export { path2usb };
这是我从console.log得到的: