TOML vs JSON: Complete Comparison and Node.js Usage Guide
TOML vs JSON: Complete Comparison and Node.js Usage Guide
Configuration files are essential in modern development. Two popular formats, TOML and JSON, serve different purposes and have distinct advantages. This guide will help you understand when to use each format and how to work with them in Node.js.
What is TOML?
TOML (Tom's Obvious, Minimal Language) is a configuration file format designed to be easy to read and write. It was created by Tom Preston-Werner, co-founder of GitHub.
TOML Example
1# config.toml2title = "My Application"3version = "1.0.0"4 5[database]6host = "localhost"7port = 54328username = "admin"9password = "secret123"10ssl = true11 12[server]13host = "0.0.0.0"14port = 300015timeout = 30What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that's widely used for APIs, configuration files, and data storage.
JSON Example
1{2 "title": "My Application",3 "version": "1.0.0",4 "database": {5 "host": "localhost",6 "port": 5432,7 "username": "admin",8 "password": "secret123",9 "ssl": true10 },11 "server": {12 "host": "0.0.0.0",13 "port": 3000,14 "timeout": 3015 },Key Differences
1. Readability
TOML:
JSON:
2. Data Types
TOML Supports:
JSON Supports:
3. Comments
TOML:
1# This is a comment2name = "value" # Inline commentJSON:
1{2 // Comments are not officially supported3 "name": "value"4}4. Use Cases
TOML is better for:
JSON is better for:
Working with TOML in Node.js
Installation
1npm install @iarna/toml2# or3npm install tomlUsing @iarna/toml (Recommended)
1const fs = require('fs');2const TOML = require('@iarna/toml');3 4// Reading TOML file5try {6 const tomlContent = fs.readFileSync('config.toml', 'utf-8');7 const config = TOML.parse(tomlContent);8 9 console.log(config.title);10 console.log(config.database.host);11 console.log(config.users);12} catch (error) {13 console.error('Error parsing TOML:', error);14}15 Complete TOML Example
1// config-loader.js2const fs = require('fs');3const path = require('path');4const TOML = require('@iarna/toml');5 6class ConfigLoader {7 constructor(configPath) {8 this.configPath = configPath;9 this.config = null;10 }11 12 load() {13 try {14 const content = fs.readFileSync(this.configPath, 'utf-8');15 this.config = TOML.parse(content);Working with JSON in Node.js
Native JSON Support
1const fs = require('fs');2 3// Reading JSON file4try {5 const jsonContent = fs.readFileSync('config.json', 'utf-8');6 const config = JSON.parse(jsonContent);7 8 console.log(config.title);9 console.log(config.database.host);10} catch (error) {11 console.error('Error parsing JSON:', error);12}13 14// Writing JSON file15const config = {Advanced JSON Handling
1// json-utils.js2const fs = require('fs').promises;3const path = require('path');4 5class JSONConfigManager {6 constructor(configPath) {7 this.configPath = configPath;8 this.config = null;9 }10 11 async load() {12 try {13 const content = await fs.readFile(this.configPath, 'utf-8');14 this.config = JSON.parse(content);15 return this.config;Converting Between TOML and JSON
TOML to JSON
1const fs = require('fs');2const TOML = require('@iarna/toml');3 4function tomlToJson(tomlPath, jsonPath) {5 try {6 const tomlContent = fs.readFileSync(tomlPath, 'utf-8');7 const parsed = TOML.parse(tomlContent);8 const jsonString = JSON.stringify(parsed, null, 2);9 fs.writeFileSync(jsonPath, jsonString);10 console.log('Converted TOML to JSON successfully');11 } catch (error) {12 console.error('Conversion error:', error);13 }14}15 JSON to TOML
1const fs = require('fs');2const TOML = require('@iarna/toml');3 4function jsonToToml(jsonPath, tomlPath) {5 try {6 const jsonContent = fs.readFileSync(jsonPath, 'utf-8');7 const parsed = JSON.parse(jsonContent);8 const tomlString = TOML.stringify(parsed);9 fs.writeFileSync(tomlPath, tomlString);10 console.log('Converted JSON to TOML successfully');11 } catch (error) {12 console.error('Conversion error:', error);13 }14}15 Real-World Examples
Example 1: Express.js Configuration
Using TOML (config.toml):
1[app]2name = "My Express App"3env = "production"4port = 30005 6[database]7type = "postgresql"8host = "localhost"9port = 543210name = "mydb"11user = "admin"12password = "secret"13 14[redis]15host = "localhost"Using JSON (config.json):
1{2 "app": {3 "name": "My Express App",4 "env": "production",5 "port": 30006 },7 "database": {8 "type": "postgresql",9 "host": "localhost",10 "port": 5432,11 "name": "mydb",12 "user": "admin",13 "password": "secret"14 },15 "redis": {Loading in Express.js:
1// Using TOML2const TOML = require('@iarna/toml');3const fs = require('fs');4const config = TOML.parse(fs.readFileSync('config.toml', 'utf-8'));5 6// Using JSON7const config = require('./config.json');8 9// Express app setup10const express = require('express');11const app = express();12 13app.listen(config.app.port, () => {14 console.log(`${config.app.name} running on port ${config.app.port}`);15});Example 2: Environment-Specific Configuration
1// config-loader.js2const fs = require('fs');3const TOML = require('@iarna/toml');4 5function loadConfig(env = 'development') {6 const configPath = `config.${env}.toml`;7 8 if (!fs.existsSync(configPath)) {9 throw new Error(`Config file ${configPath} not found`);10 }11 12 const content = fs.readFileSync(configPath, 'utf-8');13 const config = TOML.parse(content);14 15 // Override with environment variablesExample 3: Package Configuration
package.toml (alternative to package.json):
1[package]2name = "my-project"3version = "1.0.0"4description = "My awesome project"5main = "index.js"6 7[scripts]8start = "node index.js"9test = "jest"10build = "webpack"11 12[dependencies]13express = "^4.18.0"14lodash = "^4.17.21"15 Performance Comparison
Parsing Speed
1const fs = require('fs');2const TOML = require('@iarna/toml');3 4// Benchmark function5function benchmark(name, fn, iterations = 1000) {6 const start = process.hrtime.bigint();7 for (let i = 0; i < iterations; i++) {8 fn();9 }10 const end = process.hrtime.bigint();11 const duration = Number(end - start) / 1000000; // Convert to milliseconds12 console.log(`${name}: ${duration.toFixed(2)}ms (${(duration / iterations).toFixed(4)}ms per operation)`);13}14 15// Test filesResults:
When to Use Each Format
Use TOML When:
Use JSON When:
Best Practices
TOML Best Practices
1# Use comments to document configuration2# Database connection settings3[database]4# PostgreSQL connection string5host = "localhost"6port = 54327 8# Use tables for logical grouping9[server.production]10port = 808011 12[server.development]13port = 300014 15# Use arrays for multiple valuesJSON Best Practices
1{2 "version": "1.0.0",3 "config": {4 "database": {5 "host": "localhost",6 "port": 54327 }8 },9 "features": {10 "enabled": [11 "auth",12 "logging"13 ],14 "disabled": [15 "debug"16 ]17 }18}Migration Guide
Migrating from JSON to TOML
1// migrate-to-toml.js2const fs = require('fs');3const TOML = require('@iarna/toml');4 5function migrateJsonToToml(jsonPath, tomlPath) {6 const jsonContent = fs.readFileSync(jsonPath, 'utf-8');7 const jsonData = JSON.parse(jsonContent);8 const tomlContent = TOML.stringify(jsonData);9 fs.writeFileSync(tomlPath, tomlContent);10 console.log(`Migrated ${jsonPath} to ${tomlPath}`);11}12 13migrateJsonToToml('package.json', 'package.toml');Migrating from TOML to JSON
1// migrate-to-json.js2const fs = require('fs');3const TOML = require('@iarna/toml');4 5function migrateTomlToJson(tomlPath, jsonPath) {6 const tomlContent = fs.readFileSync(tomlPath, 'utf-8');7 const tomlData = TOML.parse(tomlContent);8 const jsonContent = JSON.stringify(tomlData, null, 2);9 fs.writeFileSync(jsonPath, jsonContent);10 console.log(`Migrated ${tomlPath} to ${jsonPath}`);11}12 13migrateTomlToJson('config.toml', 'config.json');Conclusion
Both TOML and JSON have their place in modern development:
Key Takeaways:
For Node.js applications, you can use both formats effectively. TOML is great for application configuration, while JSON remains the standard for APIs and data exchange.
Additional Resources
Happy coding!
Enjoyed this article?
Support our work and help us create more free content for developers.
Stay Updated
Get the latest articles and updates delivered to your inbox.