jsonroutedb
Version:
A simple Node.js package to access non-binary files using a path-like string.
74 lines (67 loc) • 2.6 kB
JavaScript
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
// Define a base directory in the user's home directory for your databases
const BASE_DATA_PATH = path.join(os.homedir(), '.jsonroutedb_data');
async function executeCommand(commandString) {
const parts = commandString.split(/\s+/); // Split by whitespace
const command = parts[0].toUpperCase();
const args = parts.slice(1);
switch (command) {
case 'CHOOSE':
// Implement your existing choose logic here, adapting to the new command structure
const choosePath = args.slice(2).join(' ').replace(/ TO /g, path.sep) + '.json'; // Example adaptation
return readFileContent(path.join(BASE_DATA_PATH, choosePath));
case 'CREATE':
if (args[0].toUpperCase() === 'DATABASE') {
const folderName = args[1];
return createDatabase(path.join(BASE_DATA_PATH, folderName));
} else if (args[0].toUpperCase() === 'FOLDER') {
const folderPath = path.join(BASE_DATA_PATH, ...args.join(' ').split(' TO ').map(part => part.trim()));
return createFolder(folderPath);
}
break;
case 'MIN':
case 'MAX':
case 'AVERAGE':
// Implement logic to read structured data from a file and perform calculations
// This will depend heavily on the format of your data files
break;
default:
return 'Unknown command';
}
return null;
}
async function readFileContent(filePath) {
try {
const data = await fs.readFile(filePath, 'utf8');
return data;
} catch (error) {
console.error('Error reading file:', error.message);
return null;
}
}
async function createDatabase(folderPath) {
try {
await fs.mkdir(folderPath, { recursive: true });
return `Database (folder) created at: ${folderPath}`;
} catch (error) {
console.error('Error creating folder:', error.message);
return `Error creating database: ${error.message}`;
}
}
async function createFolder(folderPath) {
try {
await fs.mkdir(folderPath, { recursive: true });
return `Folder created at: ${folderPath}`;
} catch (error) {
console.error('Error creating folder:', error.message);
return `Error creating folder: ${error.message}`;
}
}
module.exports = {
choose: (pathString) => executeCommand(`CHOOSE FROM ${pathString}`), // Adapt your existing choose
query: executeCommand, // A more general function for all commands
createDatabase: (dbName) => executeCommand(`CREATE DATABASE ${dbName}`),
createFolder: (folderPath) => executeCommand(`CREATE FOLDER ${folderPath}`)
};