1. tosource
toSource converts JavaScript objects back to source
tosource
Package: tosource
Created by: marcello3d
Last modified: Mon, 27 Jun 2022 18:54:32 GMT
Version: 2.0.0-alpha.3
Downloads: 1,142,917
Repository: https://github.com/marcello3d/node-tosource

Install

npm install tosource
yarn add tosource

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.

RELATED POST

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Enhancing Vue.js Development: Harnessing the Potential of Vue-Loader

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Simplify Data Validation in Vue.js: A Step-by-Step Guide to Using Regex

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Troubleshooting Made Easy: Common Issues and Solutions with vue-loader Without vue-cli

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Optimizing Webpack 4 with Vue CLI 3: Disabling the Cache-Loader

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin

Step-by-Step Guide: How to Add a Function to Your Vuex Plugin