Node.js JSON storage

NyaDB

A tiny file-backed database for projects that need readable JSON files, simple methods, and safer defaults without adding a database server.

npm version npm unpacked size npm downloads license Node.js version 12 or newer
npm install @decaded/nyadb
NyaDB/users.json
users.json 312 B
settings.json 128 B
cache.json 84 B
{
	"ada": {
		"role": "admin",
		"active": true
	},
	"linus": {
		"role": "maintainer",
		"active": true
	}
}
Validated names Path traversal protection is enabled by default.
Atomic writes Temp-file writes help protect data during updates.
Typed API TypeScript definitions ship with the package.

Install

What NyaDB creates in your project.

Node.js requirement

NyaDB supports Node.js >=12.x. It is published as a CommonJS package and can be required directly from Node projects.

Storage layout

Every database is stored as a separate JSON file inside a NyaDB folder in your project's root directory.

Default setup

Creating a new instance applies configuration, prepares the storage folder, and loads the available database files.

Install
npm install @decaded/nyadb
Initialize
const NyaDB = require('@decaded/nyadb');
const nyadb = new NyaDB();

Use cases

Use NyaDB when local JSON is the right shape.

Good fit

  • Small bots, scripts, CLI tools, and prototypes.
  • Project-local settings, feature flags, and lightweight caches.
  • Readable JSON files you may inspect or edit by hand.
  • Apps that want simple methods without running a database server.

Reach for something else

  • Large production datasets with complex queries or indexes.
  • High-write workloads where many processes write at the same time.
  • Shared remote storage, replication, or multi-user transactional data.
  • Data that needs database-level access control or advanced migrations.

Quick start

Readable JSON, direct methods.

index.js
const NyaDB = require('@decaded/nyadb');
const nyadb = new NyaDB();

nyadb.create('users');
nyadb.set('users', {
	ada: { role: 'admin', active: true },
	linus: { role: 'maintainer', active: true },
});

console.log(nyadb.get('users'));
NyaDB/users.json
{
	"ada": {
		"role": "admin",
		"active": true
	},
	"linus": {
		"role": "maintainer",
		"active": true
	}
}

Tutorial

Build a tiny database flow.

01

Create a database

create returns true when the database is created and false if it already exists or fails validation.

nyadb.create('test');
02

Insert JSON data

Use plain serializable objects. With validation enabled, circular data is rejected before it can be written.

const mockDatabase = {
	yellow: ['banana', 'citrus'],
	red: ['apple', 'paprika'],
};

nyadb.set('test', mockDatabase);
03

Read it back

get returns the object for an existing database, while getList returns every database name.

nyadb.get('test');
// {
//   yellow: ['banana', 'citrus'],
//   red: ['apple', 'paprika'],
// }

nyadb.getList();
// ['test']
04

Check existence

exists returns true when the database file is available and false otherwise.

if (nyadb.exists('test')) {
	console.log('Database exists!');
}
05

Clear or rename

clear keeps the file and resets it to {}. rename returns false if the source is missing or the destination exists.

nyadb.clear('test');
nyadb.rename('test', 'newName');
06

Delete when done

delete removes the database file and returns whether the operation succeeded.

nyadb.delete('test');

Recipes

Common patterns you can paste into a small project.

User settings
nyadb.create('settings');
nyadb.set('settings', {
	theme: 'dark',
	notifications: true,
});

const settings = nyadb.get('settings');
Feature flags
nyadb.create('features');
nyadb.set('features', {
	newDashboard: false,
	betaTools: true,
});

const flags = nyadb.get('features');
Local cache
nyadb.create('cache');
nyadb.set('cache', {
	usersUpdatedAt: Date.now(),
	users: [],
});

const status = nyadb.sizeStatus('cache');

Playground

Tap the API and watch the file state change.

NyaDB/users.json ready
Ready to run a method.

API

Small surface, predictable behavior.

create(name)

Creates a database file when it does not already exist.

set(name, data)

Writes JSON data and batches rapid updates with the debounce setting.

get(name)

Returns the database object, or false when the name is missing.

getList()

Lists available database names from the project-local NyaDB folder.

size(name)

Reports bytes and formatted file sizes for one, many, or all databases.

sizeStatus(name)

Returns status labels such as ok, warning, and critical.

clear(name)

Preserves the file while resetting the database contents to {}.

rename(oldName, newName)

Moves a database to a new valid name when that destination is free.

delete(name)

Deletes an existing database file and returns false when it cannot be removed.

exists(name)

Checks whether a database is currently loaded by name.

Sizes

Inspect storage before it surprises you.

Size checks
const size = nyadb.size('test');
console.log(size);
// { name: 'test', bytes: 1234, formatted: '1.21 KB' }

const sizes = nyadb.size(['test', 'users']);
console.log(sizes.total.formatted);
console.log(sizes.databases.test.formatted);

const allSizes = nyadb.size();
console.log(allSizes.databases);
Status checks
const status = nyadb.sizeStatus('test');
console.log(status);
// {
//   name: 'test',
//   bytes: 1234,
//   formatted: '1.21 KB',
//   percentOfLimit: 0.01,
//   status: 'ok'
// }

const allStatuses = nyadb.sizeStatus();
console.log(allStatuses.total.status);
// 'ok', 'warning', 'grace', 'critical', or 'unknown'

Configuration

Security-minded defaults, adjustable when needed.

Setting Default Options Purpose
formattingEnabled true false Enables or disables formatting of stored JSON output.
formattingStyle tab space Chooses tab or space indentation for stored JSON.
indentSize 4 Any non-negative integer Sets space indentation size when formattingStyle is space.
encoding utf8 Any valid Node.js encoding Controls file input and output encoding.
enableConsoleLogs false true Enables console logging. Errors are logged regardless of this setting.
logLevel warn error, warn, info, debug Filters console output when logs are enabled. Priority is error, warn, info, debug.
validateInput true false Validates names and data before file operations.
useAtomicWrites true false Writes through a temporary file before rename.
maxFileSize 100 Any non-negative integer Tracks file usage against a megabyte limit.
writeDebounce 10 Any non-negative integer Batches rapid write operations in milliseconds.
Custom configuration
const nyadb = new NyaDB({
	formattingStyle: 'space',
	indentSize: 5,
	enableConsoleLogs: true,
	logLevel: 'info',
});

Configuration notes

Changes apply when the instance initializes. To return to the default values, remove the setting from your config object.

useAtomicWrites requires validateInput: true. Setting atomic writes to true while validation is false throws a configuration error.

Security

Version 5 enables protection by default.

Recommended
const nyadb = new NyaDB();
// validateInput: true
// useAtomicWrites: true
Last resort only
const nyadb = new NyaDB({
	validateInput: false,
	useAtomicWrites: false,
});
Security warning

Disabling validateInput may expose your application to path traversal vulnerabilities. Only disable it when you fully control every database name.

Migration

Upgrade cleanly from older versions.

From v4.0.0 to v5.0.0

Version 5.0.0 is a major release. validateInput and useAtomicWrites now default to true.

Valid names using letters, numbers, dots, dashes, or underscores continue to work without changes.

Invalid database names

Names with path separators or parent directory references should be renamed. For example, replace ../data/users with users.

If those old JSON files already exist and you want to keep using them, move them manually into the project NyaDB folder with the new valid file names.

// Before
nyadb.create('../data/users');

// After
nyadb.create('users');

From v3.x or earlier

NyaDB version 4+ stores each database as its own JSON file. Older database.json storage is automatically split into multiple files.

This migration is one-way. The original file is backed up as database_backup.json inside the NyaDB folder, but creating your own backup before upgrading is recommended.