JavaScript Stringify
The `javascript-stringify` library provides a function, `stringify`, that converts JavaScript values into a string representation that can be safely `eval`'d back into JavaScript, in contrast to `JSON.stringify` which outputs JSON. It supports serializing a wider range of JavaScript types, including regular expressions, `Date` objects, `Number` objects, `Error`, `Map`, `Set`, and most notably, functions (including ES methods, async, and generator functions). It also handles circular references by default omitting them or, with an option, restoring them via an IIFE. The current stable version is 2.1.0. Releases appear driven by bug fixes and feature enhancements rather than a strict cadence, with significant changes like TypeScript rewrite and ESM transition occurring in major versions. Its primary differentiator is the ability to produce evaluable JavaScript code, making it useful for scenarios like code generation or transmitting configuration that includes functional logic.
Common errors
-
TypeError: (0 , javascript_stringify__WEBPACK_IMPORTED_MODULE_0__.stringify) is not a function
cause Incorrect import statement after v2.0.0, attempting to use `require` or a default import when `stringify` is a named export.fixEnsure you are using `import { stringify } from 'javascript-stringify';` for ESM or `const { stringify } = require('javascript-stringify');` for CommonJS. -
TypeError: Converting circular structure to JSON
cause This error typically occurs when using `JSON.stringify` with circular references. If you intended to use `javascript-stringify` but somehow invoked `JSON.stringify`, this would be the symptom.fixEnsure you are correctly calling `javascript-stringify`'s `stringify` function. If you need circular references restored, use the `references: true` option with `javascript-stringify`.
Warnings
- breaking The package was rewritten in TypeScript and changed its export mechanism. The primary `stringify` function is now a named export. Code relying on `require('javascript-stringify')` to get the function directly will break.
- breaking The `new Buffer()` constructor was deprecated in Node.js and has been removed from the package's internal implementation. While this might not directly break user code, it ensures compatibility with modern Node.js environments. If your own code still uses `new Buffer()`, it's a good time to update.
- gotcha By default, circular and repeated references in an object are removed during stringification to prevent infinite loops. This differs from `JSON.stringify` which would throw a `TypeError`. If you need to restore these references, you must enable the `references` option.
- gotcha The `maxDepth` and `maxValues` options provide safeguards against stringifying extremely large or deeply nested objects, potentially truncating the output. Be aware of these defaults if your expected output is truncated.
Install
-
npm install javascript-stringify -
yarn add javascript-stringify -
pnpm add javascript-stringify
Imports
- stringify
const stringify = require('javascript-stringify');import { stringify } from 'javascript-stringify'; - StringifyOptions
import type { StringifyOptions } from 'javascript-stringify';
Quickstart
import { stringify } from 'javascript-stringify';
const exampleData = {
id: 1,
name: 'Complex Object',
date: new Date('2023-01-15T10:00:00Z'),
regex: /\btest\b/gi,
status: null,
computed: function(a, b) { return a + b; },
nested: {
value: 42,
metadata: new Map([['key1', 'val1'], ['key2', 'val2']])
}
};
// Add a circular reference to demonstrate handling
exampleData.selfRef = exampleData;
console.log('Default stringify (circular references removed):');
console.log(stringify(exampleData));
console.log('\nStringify with restored references (uses IIFE):');
console.log(stringify(exampleData, null, 2, { references: true }));
console.log('\nStringify with maxDepth:');
console.log(stringify(exampleData, null, null, { maxDepth: 2 }));
const replacerExample = stringify(['foo', 123, 'bar'], function (value, indent, stringify) {
if (typeof value === 'string') {
return '"' + value.toUpperCase() + '"';
}
return stringify(value);
});
console.log('\nStringify with custom replacer:');
console.log(replacerExample);