anysafe
v1.0.2
Published
Safely converts any JavaScript value into a string, integer, array, or JSON — namespace and fluent API
Maintainers
Readme
anysafe
Safely converts any JavaScript value into a string, integer, array, or JSON string — never throws, always falls back to a sensible default.
This is a thin wrapper bundling to-safe-string, to-safe-integer, to-safe-array, and to-safe-json into a single install. Each of those packages also works completely standalone if you only need one conversion.
Installation
npm install anysafeUsage
Two equivalent styles — pick whichever reads better in context.
Namespace style
const anysafe = require('anysafe');
anysafe.toSafeString(42); // "42"
anysafe.toSafeInteger('42px'); // 42
anysafe.toSafeArray('[1,2,3]'); // [1, 2, 3]
anysafe.toSafeJson([1, 2, 3]); // '[1,2,3]'Fluent style
const safe = require('anysafe');
safe(42).toString(); // "42"
safe('42px').toInteger(); // 42
safe('[1,2,3]').toArray(); // [1, 2, 3]
safe([1, 2, 3]).toJson(); // '[1,2,3]'Useful when converting the same value multiple ways:
const raw = req.body.count;
safe(raw).toInteger(); // 42
safe(raw).toString(); // "42"Fallback values
Both styles accept an optional fallback, passed straight through to the underlying package:
anysafe.toSafeInteger('abc', -1); // -1
safe('abc').toInteger(-1); // -1Using a single conversion only?
If you only need one of these conversions, install the individual package instead — it has no dependencies and a smaller footprint:
npm install to-safe-integerAPI
anysafe(value)
Returns an object with chainable methods: toString(fallback), toInteger(fallback), toArray(fallback), toJson(fallback).
anysafe.toSafeString(value, fallback)
anysafe.toSafeInteger(value, fallback)
anysafe.toSafeArray(value, fallback)
anysafe.toSafeJson(value, fallback)
Same functions as the standalone packages, attached directly to anysafe for namespace-style use.
License
MIT © Toby Maxham
