tosource: Object to Source Code Converter

2.0.0-alpha.3 · active · verified Sun Apr 19

tosource is a utility library for JavaScript that serializes complex JavaScript objects, including functions, Date objects, RegExp instances, Maps, Sets, sparse arrays, NaN, Infinity, undefined, and negative zero, into their equivalent JavaScript source code string representations. This extends beyond the capabilities of JSON.stringify, which only handles a subset of these types. The package is currently in a pre-release alpha phase (v2.0.0-alpha.3), indicating active development. It is designed to facilitate sharing trusted data structures and even code between Node.js environments and browsers, useful for isomorphic applications. While there isn't an explicit release cadence, the recent alpha releases suggest ongoing improvements in functionality and toolchain, including TypeScript support and ESM exports.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates serialization of various JavaScript types, including functions, regular expressions, dates, Map, Set, and handling of circular references by marking them.

import toSource from 'tosource';

const complexObject = [
  4,
  5,
  6,
  'hello',
  {
    a: 2,
    b: 3,
    '1': 4,
    if: 5,
    yes: true,
    no: false,
    nan: NaN,
    infinity: Infinity,
    undefined: undefined,
    null: null,
    foo: function (bar) {
      console.log('woo! a is ' + this.a);
      console.log('and bar is ' + bar);
    },
  },
  /we$/gi,
  new Date('Wed, 09 Aug 1995 00:00:00 GMT'),
  new Map([['key1', 'value1'], ['key2', 123]]),
  new Set([1, 2, 'three'])
];

console.log('Serialized Complex Object:\n', toSource(complexObject));

// Example with a circular reference (tosource handles it by marking)
const objWithCircularRef = { id: 1 };
objWithCircularRef.self = objWithCircularRef;
objWithCircularRef.nested = { child: objWithCircularRef };

console.log('\nSerialized Object with Circular Reference:\n', toSource(objWithCircularRef));

view raw JSON →