tosource: Object to Source Code Converter
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
-
ReferenceError: toSource is not defined
cause Incorrect import statement or attempting to use `toSource` before it's properly imported/required.fixFor ESM, use `import toSource from 'tosource';`. For CommonJS, use `const toSource = require('tosource');`. Ensure `toSource` is within scope. -
TypeError: tosource is not a function
cause Often occurs when using a named import (e.g., `import { toSource } from 'tosource';`) instead of the default import for ESM, or a destructured require for CJS, as `toSource` is a default export.fixUse the default import for ESM (`import toSource from 'tosource';`) or a standard `require` for CJS (`const toSource = require('tosource');`). -
ERR_REQUIRE_ESM: Must use import to load ES Module
cause Attempting to use `require()` to import `tosource` in a pure ESM context (e.g., in a package configured with `"type": "module"` in `package.json`).fixSwitch to `import toSource from 'tosource';` if your environment supports ESM. If you must use CommonJS, ensure your environment is configured for CJS modules. -
Node.js version mismatch
cause The installed Node.js version is below the minimum requirement (10.x) for `tosource` v2.x.fixUpgrade your Node.js runtime to version 10 or higher. You can use tools like `nvm` (Node Version Manager) to manage multiple Node.js versions.
Warnings
- breaking Version 2.x introduces a minimum Node.js requirement of 10.x. Older Node.js environments are not supported.
- breaking The handling of negative zero (`-0`) was fixed in `v2.0.0-alpha.3` and now correctly uses `Object.is` for comparison during serialization. This might subtly change output if your application relied on previous serialization behavior for negative zero.
- gotcha Functions are serialized by calling their `toString()` method. This means only the function's source code is preserved; its lexical environment (closures) and bound `this` context are not serialized.
- gotcha Multiple references to the same object in the input will result in multiple independent copies in the serialized output, rather than maintaining shared references.
- gotcha Circular references within objects are detected and serialized as `{$circularReference:true}`. Attempting to deserialize and execute this without custom handling will result in an object literal, not the original circular structure.
- gotcha The package is currently in an alpha state (`2.0.0-alpha.3`). APIs might change without a full major version bump, and it may contain unresolved bugs. It is not recommended for critical production environments without thorough testing.
Install
-
npm install tosource -
yarn add tosource -
pnpm add tosource
Imports
- toSource (ESM Default)
import { toSource } from 'tosource';import toSource from 'tosource';
- toSource (CommonJS)
const { toSource } = require('tosource');const toSource = require('tosource'); - Type Definition
import type toSource from 'tosource';
Quickstart
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));