Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

tosource

marcello3d1.1m2.0.0-alpha.3TypeScript support: included

toSource converts JavaScript objects back to source

source, tosource, json, javascript object, object

readme

node-tosource

Actions Status npm version codecov

toSource is a super simple function that converts JavaScript objects back to source code.

Introduction

Motivation: JSON doesn't support serializing functions, dates, or regular expressions. I wanted a quick and simple way to push trusted data structures with code from Node down to the browser.

This should make it easier to share code and modules between the server and client.

Installation

npm install tosource

Examples

The following code:

import toSource from 'tosource';

console.log(
  toSource([
    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 ' + a);
        console.log('and bar is ' + bar);
      },
    },
    /we$/gi,
    new Date('Wed, 09 Aug 1995 00:00:00 GMT'),
  ]),
);

Output:

[ 4,
  5,
  6,
  "hello",
  { 1:4,
    a:2,
    b:3,
    "if":5,
    yes:true,
    no:false,
    nan:NaN,
    infinity:Infinity,
    "undefined":undefined,
    "null":null,
    foo:function (bar) {
        console.log('woo! a is ' + a);
        console.log('and bar is ' + bar);
      } },
  /we$/gi,
  new Date(807926400000) ]

See tosource.test.ts for more examples.

Supported Types

  • numbers (including NaN, Infinity, and -0)
  • strings
  • Arrays (including sparse arrays)
  • object literals
  • function
  • RegExp instances
  • Date instances
  • Map
  • Set
  • true / false
  • undefined
  • null

Notes

  • Functions are serialized with func.toString(), no closure properties are serialized
  • Multiple references to the same object become copies
  • Circular references are encoded as {$circularReference:true}

License

toSource is open source software under the zlib license.

changelog

2.0.0-alpha.3 (2021-07-31)

  • Breaking change: Requires Object.is or polyfill

2.0.0-alpha.1 (2020-03-30)

  • Breaking change: Requires Node 10.x
  • migrate toolchain: TypeScript, prettier, eslint, jest, rollup
  • export TypeScript types and esm export
  • add support for Map, Set, negative zero, sparse arrays
  • serialize numeric object keys as numbers (e.g. {'1':2} becomes {1:2})

1.0.0 (2015-09-03)

  • added changelog
  • fixed RegExp escaping of / on node 0.10
  • added standard for code style/eslint

v0.1.3 (2014-10-08)

  • use toString for functions

v0.1.2 (2014-05-14)

  • fixes circular reference bug

v0.1.1 (2011-04-24)

  • initial release