What is javascript-stringify?
The javascript-stringify npm package is designed to safely serialize JavaScript expressions to a string representation that can be readily parsed by JavaScript engines. This is particularly useful for scenarios where you need to generate code or serialize objects and functions in a way that retains their behavior and structure.
What are javascript-stringify's main functionalities?
Serialize Objects
This feature allows the serialization of objects into a string format that can be evaluated by JavaScript. Useful for logging or storing configurations.
const stringify = require('javascript-stringify');
const object = { a: 1, b: 'text', c: true };
const stringified = stringify(object);
console.log(stringified);
Serialize Functions
Enables the serialization of functions, preserving the function's structure and content. Ideal for scenarios where functions need to be transmitted or stored and later reconstructed.
const stringify = require('javascript-stringify');
function exampleFunction() {
return 'Hello, World!';
}
const stringified = stringify(exampleFunction);
console.log(stringified);
Custom Serialization
Supports custom serialization options such as limiting the depth of serialization. This is useful for complex objects where deep nesting occurs.
const stringify = require('javascript-stringify');
const object = { a: 1, b: undefined, c: function() {} };
const stringified = stringify(object, null, null, { maxDepth: 3 });
console.log(stringified);
Other packages similar to javascript-stringify
json-stringify-safe
Similar to javascript-stringify, json-stringify-safe handles circular dependencies gracefully when serializing objects to JSON. However, it does not handle functions or provide options for custom serialization depth.
serialize-javascript
This package offers functionality similar to javascript-stringify by allowing serialization of objects including functions and regex expressions. It provides XSS protection which javascript-stringify does not focus on.
JavaScript Stringify
Stringify is to eval
as JSON.stringify
is to JSON.parse
.
Installation
npm install javascript-stringify --save
Usage
import { stringify } from "javascript-stringify";
The API is similar JSON.stringify
:
value
The value to convert to a stringreplacer
A function that alters the behavior of the stringification processspace
A string or number that's used to insert white space into the output for readability purposesoptions
- maxDepth (number, default: 100) The maximum depth of values to stringify
- maxValues (number, default: 100000) The maximum number of values to stringify
- references (boolean, default: false) Restore circular/repeated references in the object (uses IIFE)
- skipUndefinedProperties (boolean, default: false) Omits
undefined
properties instead of restoring as undefined
Examples
stringify({});
stringify(true);
stringify("foo");
stringify({ x: 5, y: 6 });
stringify([1, 2, 3, "string"]);
stringify({ a: { b: { c: 1 } } }, null, null, { maxDepth: 2 });
stringify({ "some-key": 10 });
stringify([/.+/gi, new Number(10), new Date()]);
var obj = { x: 10 };
obj.circular = obj;
stringify(obj);
stringify(obj, null, null, { references: true });
stringify({ a: 2 }, null, " ");
stringify({ uno: 1, dos: 2 }, null, "\t");
stringify(["test", "string"], function (value, indent, stringify) {
if (typeof value === "string") {
return '"' + value.replace(/"/g, '\\"') + '"';
}
return stringify(value);
});
Formatting
You can use your own code formatter on the result of javascript-stringify
. Here is an example using eslint:
const { CLIEngine } = require("eslint");
const { stringify } = require("javascript-stringify");
const { APP_ROOT_PATH, ESLINTRC_FILE_PATH } = require("./constants");
const ESLINT_CLI = new CLIEngine({
fix: true,
cwd: APP_ROOT_PATH,
configFile: ESLINTRC_FILE_PATH,
});
module.exports = (objectToStringify) => {
return ESLINT_CLI.executeOnText(stringify(objectToStringify)).results[0]
.output;
};
License
MIT