@buudata/buudata
v1.0.0
Published
Minimalist, dependency-free parser/stringifier for commentable JSON (BuuD), using only Node.js core modules (fs, path).
Maintainers
Readme
BuuData
🚀 Features
- 💬 Comment Support - Both
//and/* */style comments - 📄 JSON Compatible - Standard JSON with comment extensions
- 🚫 Zero Dependencies - Uses only Node.js core modules (fs, path)
- ⚡ Lightweight - Minimal footprint
- 🔧 Simple API - Easy parse/stringify methods
- 📁 File Operations - Direct file load/save functionality
- 🛡️ Type Safe - Built-in error handling
- 🌐 Universal - Works in any Node.js environment
- 📦 CommonJS - Standard require() syntax
📦 Installation
# Using npm
npm install @buudata/buudata
# Using yarn
yarn add @buudata/buudata
# Using pnpm
pnpm add @buudata/buudata💡 Quick Start
const { buuDATA } = require('@buudata/buudata');
// Parse BuuD string (JSON with comments)
const buudString = `
// Configuration file
{
"name": "MyApp", // Application name
"version": "1.0.0",
/*
* Database settings
*/
"database": {
"host": "localhost", // Development server
"port": 3306
}
}`;
// Parse to JavaScript object
const config = buuDATA.parse(buudString);
console.log(config.name); // "MyApp"
// Stringify with comments
const data = { name: "Test", version: "1.0.0" };
const output = buuDATA.stringify(data, [
"Generated configuration",
"Created: " + new Date().toISOString()
]);
console.log(output);
// Output:
// // Generated configuration
// // Created: 2025-11-03T...
//
// {
// "name": "Test",
// "version": "1.0.0"
// }🎯 BuuD Format Examples
Standard JSON File (users.json)
{
"version": "1.0",
"settings": {
"beta": true
},
"users": [
{
"id": 1,
"name": "user1"
},
{
"id": 2,
"name": "user2"
}
]
}BuuD Format File (users.buud)
{
"version": "1.0", // die Version
"settings": { /* * die settings
* ob der User Beta ist
* */
"beta": true
},
"users": [
{
"id": 1, // User 1
"name": "user1"
},
{
"id": 2, // User 2
"name": "user2"
}
]
}Key Differences:
- ✅ Single-line comments with
// - ✅ Multi-line comments with
/* */ - ✅ Inline comments after properties
- ✅ Header comments for documentation
- ✅ Full JSON compatibility when comments are removed
🔧 API Reference
buuDATA.parse(buudString): Object
Parses a BuuD string (JSON with comments) into a JavaScript object.
const { buuDATA } = require('@buudata/buudata');
const buudString = `
// App configuration
{
"name": "MyApp", // Application name
"debug": true
}`;
const config = buuDATA.parse(buudString);
// Returns: { name: "MyApp", debug: true }Parameters:
buudString(string): The BuuD formatted string to parse
Returns: JavaScript object
Throws:
TypeErrorif input is not a stringSyntaxErrorif JSON is invalid after comment removal
buuDATA.stringify(data, comments?): string
Converts a JavaScript object to a BuuD formatted string with optional comments.
const data = {
name: "MyProject",
version: "2.0.0",
features: ["parsing", "comments"]
};
// With single comment
const result1 = buuDATA.stringify(data, "Project configuration");
// With multiple comments
const result2 = buuDATA.stringify(data, [
"MyProject Configuration",
"Generated on: " + new Date().toLocaleDateString(),
"Author: HonneyBuuModz"
]);
console.log(result2);
// Output:
// // MyProject Configuration
// // Generated on: 11/3/2025
// // Author: HonneyBuuModz
//
// {
// "name": "MyProject",
// "version": "2.0.0",
// "features": [
// "parsing",
// "comments"
// ]
// }Parameters:
data(any): The JavaScript object to stringifycomments(string|string[], optional): Header comments to add
Returns: BuuD formatted string
buuDATA.file.load(filePath): Promise<Object>
Loads and parses a BuuD file from disk.
// Load configuration file
const config = await buuDATA.file.load('./config.buud');
console.log(config);
// Load with absolute path
const data = await buuDATA.file.load('/path/to/data.buud');Parameters:
filePath(string): Path to the BuuD file (relative or absolute)
Returns: Promise that resolves to the parsed JavaScript object
Throws: File system errors (file not found, permission denied, etc.)
buuDATA.file.save(filePath, data, comments?): Promise<void>
Saves a JavaScript object as a BuuD file with optional comments.
const userData = {
users: [
{ id: 1, name: "Alice", active: true },
{ id: 2, name: "Bob", active: false }
],
lastUpdate: new Date().toISOString()
};
// Save with comments
await buuDATA.file.save('./users.buud', userData, [
"User database",
"Last modified: " + new Date().toLocaleDateString()
]);
// Save without comments
await buuDATA.file.save('./data.buud', userData);Parameters:
filePath(string): Destination file pathdata(any): JavaScript object to savecomments(string|string[], optional): Header comments
Returns: Promise that resolves when file is saved
⚡ Advanced Usage
Configuration Management
const { buuDATA } = require('@buudata/buudata');
class ConfigManager {
constructor(configPath) {
this.configPath = configPath;
}
async load() {
try {
this.config = await buuDATA.file.load(this.configPath);
return this.config;
} catch (error) {
// Return default config if file doesn't exist
this.config = this.getDefaultConfig();
await this.save();
return this.config;
}
}
async save() {
const comments = [
"Application Configuration",
"Auto-generated on: " + new Date().toISOString(),
"Modify with caution!"
];
await buuDATA.file.save(this.configPath, this.config, comments);
}
get(key) {
return this.config[key];
}
set(key, value) {
this.config[key] = value;
}
getDefaultConfig() {
return {
version: "1.0.0",
debug: false,
server: {
host: "localhost",
port: 3000
},
database: {
host: "localhost",
port: 5432,
name: "myapp"
}
};
}
}
// Usage
async function main() {
const config = new ConfigManager('./app.buud');
await config.load();
console.log('Server port:', config.get('server').port);
// Update configuration
config.set('debug', true);
await config.save();
}
main();Data Processing Pipeline
const { buuDATA } = require('@buudata/buudata');
const path = require('path');
class DataProcessor {
constructor(inputDir, outputDir) {
this.inputDir = inputDir;
this.outputDir = outputDir;
}
async processFile(filename) {
const inputPath = path.join(this.inputDir, filename);
const outputPath = path.join(this.outputDir, filename.replace('.buud', '.json'));
try {
// Load BuuD file
const data = await buuDATA.file.load(inputPath);
// Process data (example: add timestamp)
data.processedAt = new Date().toISOString();
data.processor = "BuuData v1.0.0";
// Save as standard JSON
const fs = require('fs/promises');
await fs.writeFile(outputPath, JSON.stringify(data, null, 2));
console.log(`✅ Processed: ${filename}`);
return data;
} catch (error) {
console.error(`❌ Error processing ${filename}:`, error.message);
throw error;
}
}
async processDirectory() {
const fs = require('fs/promises');
const files = await fs.readdir(this.inputDir);
const buudFiles = files.filter(f => f.endsWith('.buud'));
console.log(`📁 Processing ${buudFiles.length} BuuD files...`);
const results = [];
for (const file of buudFiles) {
const result = await this.processFile(file);
results.push(result);
}
return results;
}
}
// Usage
async function batchProcess() {
const processor = new DataProcessor('./input', './output');
const results = await processor.processDirectory();
console.log(`🎉 Processed ${results.length} files successfully!`);
}
batchProcess();Database-like File Operations
const { buuDATA } = require('@buudata/buudata');
class BuuDatabase {
constructor(filePath) {
this.filePath = filePath;
this.data = { records: [], metadata: {} };
}
async initialize() {
try {
this.data = await buuDATA.file.load(this.filePath);
} catch (error) {
// Create new database file
this.data = {
records: [],
metadata: {
version: "1.0.0",
created: new Date().toISOString(),
lastModified: new Date().toISOString()
}
};
await this.save();
}
}
async save() {
this.data.metadata.lastModified = new Date().toISOString();
const comments = [
"BuuDatabase File",
"Records: " + this.data.records.length,
"Last Modified: " + new Date().toLocaleString()
];
await buuDATA.file.save(this.filePath, this.data, comments);
}
async insert(record) {
const id = this.data.records.length + 1;
const newRecord = {
id,
...record,
createdAt: new Date().toISOString()
};
this.data.records.push(newRecord);
await this.save();
return newRecord;
}
find(query) {
return this.data.records.filter(record => {
return Object.keys(query).every(key => record[key] === query[key]);
});
}
findById(id) {
return this.data.records.find(record => record.id === id);
}
async update(id, updates) {
const record = this.findById(id);
if (!record) throw new Error(`Record with id ${id} not found`);
Object.assign(record, updates, { updatedAt: new Date().toISOString() });
await this.save();
return record;
}
async delete(id) {
const index = this.data.records.findIndex(record => record.id === id);
if (index === -1) throw new Error(`Record with id ${id} not found`);
const deleted = this.data.records.splice(index, 1)[0];
await this.save();
return deleted;
}
count() {
return this.data.records.length;
}
all() {
return [...this.data.records];
}
}
// Usage
async function databaseExample() {
const db = new BuuDatabase('./users.buud');
await db.initialize();
// Insert users
const user1 = await db.insert({ name: "Alice", email: "[email protected]" });
const user2 = await db.insert({ name: "Bob", email: "[email protected]" });
console.log('Inserted users:', user1, user2);
// Query users
const allUsers = db.all();
console.log('All users:', allUsers);
// Find specific user
const alice = db.find({ name: "Alice" });
console.log('Found Alice:', alice);
// Update user
await db.update(user1.id, { email: "[email protected]" });
// Count records
console.log('Total users:', db.count());
// Delete user
await db.delete(user2.id);
console.log('Remaining users:', db.count());
}
databaseExample();🛡️ Error Handling
const { buuDATA } = require('@buudata/buudata');
async function robustExample() {
try {
// Handle invalid input type
buuDATA.parse(123); // Throws TypeError
} catch (error) {
if (error instanceof TypeError) {
console.log('Invalid input type:', error.message);
}
}
try {
// Handle invalid JSON
buuDATA.parse('{ invalid json }'); // Throws SyntaxError
} catch (error) {
if (error instanceof SyntaxError) {
console.log('Invalid JSON syntax:', error.message);
}
}
try {
// Handle file not found
await buuDATA.file.load('./nonexistent.buud');
} catch (error) {
if (error.code === 'ENOENT') {
console.log('File not found, creating default...');
const defaultData = { initialized: true };
await buuDATA.file.save('./nonexistent.buud', defaultData);
}
}
try {
// Handle permission errors
await buuDATA.file.save('/root/restricted.buud', {});
} catch (error) {
if (error.code === 'EACCES') {
console.log('Permission denied, trying alternative location...');
await buuDATA.file.save('./restricted.buud', {});
}
}
}
robustExample();🎯 Use Cases
Perfect for:
- 🔧 Configuration Files - App settings with inline documentation
- 📊 Data Storage - Lightweight JSON database with comments
- 🗃️ File-based Databases - Simple record storage
- 📝 Documentation - Self-documenting data files
- ⚙️ Build Configurations - Commented build settings
- 🎮 Game Data - Level configurations with notes
- 📋 Form Schemas - UI form definitions with explanations
- 🌐 API Configurations - Endpoint settings with descriptions
🔍 Technical Details
- ✅ Node.js Core Only - fs/promises, path modules
- ✅ CommonJS Module - Standard require() syntax
- ✅ Zero Dependencies - No external packages required
- ✅ Comment Regex - Handles both
//and/* */styles - ✅ Error Safe - Comprehensive error handling
- ✅ Path Resolution - Absolute path conversion
- ✅ UTF-8 Encoding - Full Unicode support
- ✅ Memory Efficient - Minimal memory footprint
- ✅ Cross-Platform - Works on Windows, macOS, Linux
📋 Package Contents
- 📃
src/index.js- Main BuuData library - 📜
package.json- Package configuration - 📖
README.md- This comprehensive documentation
🤝 Contributing
We welcome contributions! You can:
- 🐛 Report bugs and issues
- 💡 Suggest new features and improvements
- 🔧 Submit pull requests
- 📖 Improve documentation
- 🌟 Rate and share the package
📄 License
MIT License - Free and Open Source
This project is licensed under the MIT License, which means you are free to:
- ✅ Use - Use this library in personal and commercial projects
- ✅ Modify - Change and customize the code to fit your needs
- ✅ Distribute - Share and redistribute the library
- ✅ Private Use - Use in private projects without restrictions
- ✅ Commercial Use - Use in commercial applications and products
The only requirement is to include the original copyright notice and license terms.
