npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@lopatnov/javascripttostring

v2.1.0

Published

A TypeScript library that converts any JavaScript runtime value into its string source code representation, including objects, arrays, functions, circular references, and cross-references

Downloads

263

Readme

@lopatnov/javascripttostring

npm NPM version License TypeScript GitHub stars

A TypeScript library that converts any JavaScript runtime value into its string source code representation. Supports objects, arrays, functions, circular references, cross-references, and more.

Table of Contents

Installation

npm install @lopatnov/javascripttostring

Browser (CDN)

<script src="https://unpkg.com/@lopatnov/javascripttostring/dist/javascripttostring.umd.js"></script>

Usage

ES Modules

import javaScriptToString from "@lopatnov/javascripttostring";

CommonJS

const javaScriptToString = require("@lopatnov/javascripttostring");

Browser (UMD)

const javaScriptToString = window.javaScriptToString;

API

javaScriptToString(value, options?): string

Converts a JavaScript value to its string source code representation.

| Parameter | Type | Description | |-----------|------|-------------| | value | any | The value to convert | | options | IJ2SOptions | Optional configuration |

Returns: string - Source code representation that can be evaluated back to the original value

Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | includeFunctionProperties | boolean | true | Include function's own properties | | includeFunctionPrototype | boolean | true | Include function's prototype properties | | includeBuffers | boolean | true | Include ArrayBuffer and TypedArray contents | | nestedObjectsAmount | number | Infinity | Max depth for nested objects | | nestedArraysAmount | number | Infinity | Max depth for nested arrays | | nestedFunctionsAmount | number | Infinity | Max depth for nested functions | | throwOnNonSerializable | boolean | false | Throw an error for non-serializable values (Promise, Generator, WeakRef, WeakMap, WeakSet, FinalizationRegistry) |

Examples

Primitives

javaScriptToString("Hello world");   // '"Hello world"'
javaScriptToString(42);              // '42'
javaScriptToString(true);            // 'true'
javaScriptToString(undefined);       // 'undefined'
javaScriptToString(null);            // 'null'

Arrays

javaScriptToString(["Hello", "World"]);
// '["Hello", "World"]'

Objects

javaScriptToString({
  name: "Alex",
  friends: ["Shurik", "Hola"],
  greet: () => {
    console.log("How you doing?");
  }
});
// '{name: "Alex", friends: ["Shurik", "Hola"], greet: () => { console.log("How you doing?"); }}'

Functions with Properties

function Simple(title) {
  this.title = title || "world";
}
Simple.count = 0;
Simple.prototype.show = function () {
  Simple.count++;
  console.log("title =", this.title);
};

javaScriptToString(Simple);
// '(function(){ var Simple = function Simple(title) { ... }; Simple.count = 0; Simple.prototype.show = function(){ ... }; return Simple; }())'

Circular References

Objects that reference themselves are fully supported:

var x = [1, 2, 3];
x[0] = x;

javaScriptToString(x);
// '(function(){ var ___ref1 = [null, 2, 3]; ___ref1[0] = ___ref1; return ___ref1; }())'

Cross-References

Objects shared between different branches are preserved as references:

var shared = { value: 42 };
var obj = { a: shared, b: shared };

javaScriptToString(obj);
// Generates code where obj.a === obj.b (same reference):
// (function(){ var ___ref1 = {
//   a: { value: 42 },
//   b: null
// }; ___ref1.b = ___ref1.a; return ___ref1; }())

Using with Web Workers

Combine with @lopatnov/worker-from-string to serialize functions and data for execution in a Web Worker:

import javaScriptToString from "@lopatnov/javascripttostring";
import workerFromString from "@lopatnov/worker-from-string";

// Function with attached lookup data
function classify(value) {
  const range = classify.ranges.find(r => value >= r.min && value < r.max);
  return range ? range.label : "unknown";
}
classify.ranges = [
  { min: 0, max: 30, label: "cold" },
  { min: 30, max: 60, label: "warm" },
  { min: 60, max: 100, label: "hot" },
];

// Serialize and send to a worker
// javaScriptToString preserves the function AND its properties:
const code = javaScriptToString(classify);

const worker = workerFromString(`
  const classify = ${code};
  self.onmessage = (e) => postMessage(classify(e.data));
`);

worker.onmessage = (e) => console.log(e.data);
worker.postMessage(45); // "warm"

Restoring Values

The generated string can be evaluated back to a working JavaScript value:

var original = { name: "test" };
original.self = original;

var code = javaScriptToString(original);
var restored = Function("return " + code)();

console.log(restored.self === restored); // true
console.log(restored.name);             // "test"

Supported Types

| Type | Example | Notes | |------|---------|-------| | Primitives | string, number, boolean, undefined, null | Including -0 and NaN | | BigInt | BigInt(123) | | | Symbol | Symbol("desc"), Symbol.for("key") | Registry symbols preserved | | RegExp | /pattern/gi | lastIndex preserved when non-zero | | Date | new Date("...") | Invalid dates → new Date(NaN) | | Error | new Error(), new TypeError() | TypeError, RangeError, ReferenceError, SyntaxError, URIError, EvalError | | Array | [1, 2, 3] | Sparse arrays preserved | | Object | { key: "value" } | Including Object.create(null) | | Function | function() {}, () => {}, async function() {} | Properties and prototype included | | Generator Function | function*() {}, async function*() {} | | | Map | new Map([["key", "value"]]) | | | Set | new Set([1, 2, 3]) | | | TypedArray | Int8Array, Float64Array, etc. | | | ArrayBuffer | new ArrayBuffer(8), SharedArrayBuffer | | | DataView | new DataView(buffer) | |

Non-serializable Types

The following types cannot be serialized and return "undefined" by default. Use throwOnNonSerializable: true to throw an error instead:

Promise, Generator, WeakRef, WeakMap, WeakSet, FinalizationRegistry

Demo

Try the library interactively:

Documentation

Related Packages

| Package | Description | |---|---| | @lopatnov/worker-from-string | Create Web Workers from strings — pairs well with javaScriptToString | | @lopatnov/get-internal-type | Runtime type detection used internally by this library |

Contributing

Contributions are welcome! Please read CONTRIBUTING.md before opening a pull request.


Built With


License

Apache-2.0 © 2019–2026 Oleksandr Lopatnov · LinkedIn