Files
DRBv3/client/modules/baseUtils.mjs
2024-02-10 15:10:35 -05:00

64 lines
1.7 KiB
JavaScript

import { networkInterfaces } from 'os';
import { createHash, randomBytes } from 'crypto';
import { promises, constants } from 'fs';
import { dirname } from "path";
/**
* Check to see if the input is a valid JSON string
*
* @param {*} str The string to check for valud JSON
* @returns {true|false}
*/
export const isJsonString = (str) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
/**
* Check to see if a path exists, creating it if it does not
* @returns {undefined}
*/
export const ensureDirectoryExists = async (filePath) => {
const directory = dirname(filePath);
try {
await promises.access(directory, constants.F_OK);
} catch (error) {
await promises.mkdir(directory, { recursive: true });
}
};
/**
* Generate a unique ID for a given device, this will also be unique on the same device at a different time.
* @returns {string} A generated unique ID
*/
export const generateUniqueID = () => {
const netInterfaces = networkInterfaces();
let macAddress = '';
// Find the first non-internal MAC address
for (const key in netInterfaces) {
const iface = netInterfaces[key][0];
if (!iface.internal) {
macAddress = iface.mac;
break;
}
}
// If no non-internal MAC address is found, fallback to a random value
if (!macAddress) {
macAddress = randomBytes(6).toString('hex').toUpperCase();
}
// Use MAC address and current timestamp to create a unique ID
const timestamp = Date.now();
const uniqueID = createHash('sha256')
.update(macAddress + timestamp)
.digest('hex');
return uniqueID;
}