1 | # node-tosource
|
2 |
|
3 | [![Actions Status](https://github.com/marcello3d/node-tosource/workflows/Node%20CI/badge.svg)](https://github.com/marcello3d/node-tosource/actions)
|
4 | [![npm version](https://badge.fury.io/js/tosource.svg)](https://badge.fury.io/js/tosource)
|
5 | [![codecov](https://codecov.io/gh/marcello3d/node-tosource/branch/master/graph/badge.svg)](https://codecov.io/gh/marcello3d/node-tosource)
|
6 |
|
7 | toSource is a super simple function that converts JavaScript objects back to source code.
|
8 |
|
9 | ## Introduction
|
10 |
|
11 | Motivation: JSON doesn't support serializing functions, dates, or regular expressions. I wanted
|
12 | a quick and simple way to push trusted data structures with code from Node down to the browser.
|
13 |
|
14 | This should make it easier to share code and modules between the server and client.
|
15 |
|
16 | ## Installation
|
17 |
|
18 | ```
|
19 | npm install tosource
|
20 | ```
|
21 |
|
22 | ## Examples
|
23 |
|
24 | The following code:
|
25 |
|
26 | ```js
|
27 | import toSource from 'tosource';
|
28 |
|
29 | console.log(
|
30 | toSource([
|
31 | 4,
|
32 | 5,
|
33 | 6,
|
34 | 'hello',
|
35 | {
|
36 | a: 2,
|
37 | b: 3,
|
38 | '1': 4,
|
39 | if: 5,
|
40 | yes: true,
|
41 | no: false,
|
42 | nan: NaN,
|
43 | infinity: Infinity,
|
44 | undefined: undefined,
|
45 | null: null,
|
46 | foo: function (bar) {
|
47 | console.log('woo! a is ' + a);
|
48 | console.log('and bar is ' + bar);
|
49 | },
|
50 | },
|
51 | /we$/gi,
|
52 | new Date('Wed, 09 Aug 1995 00:00:00 GMT'),
|
53 | ]),
|
54 | );
|
55 | ```
|
56 |
|
57 | Output:
|
58 |
|
59 | ```
|
60 | [ 4,
|
61 | 5,
|
62 | 6,
|
63 | "hello",
|
64 | { 1:4,
|
65 | a:2,
|
66 | b:3,
|
67 | "if":5,
|
68 | yes:true,
|
69 | no:false,
|
70 | nan:NaN,
|
71 | infinity:Infinity,
|
72 | "undefined":undefined,
|
73 | "null":null,
|
74 | foo:function (bar) {
|
75 | console.log('woo! a is ' + a);
|
76 | console.log('and bar is ' + bar);
|
77 | } },
|
78 | /we$/gi,
|
79 | new Date(807926400000) ]
|
80 | ```
|
81 |
|
82 | See [tosource.test.ts][1] for more examples.
|
83 |
|
84 | ## Supported Types
|
85 |
|
86 | - numbers (including `NaN`, `Infinity`, and `-0`)
|
87 | - strings
|
88 | - Arrays (including sparse arrays)
|
89 | - object literals
|
90 | - function
|
91 | - `RegExp` instances
|
92 | - `Date` instances
|
93 | - `Map`
|
94 | - `Set`
|
95 | - `true` / `false`
|
96 | - `undefined`
|
97 | - `null`
|
98 |
|
99 | ## Notes
|
100 |
|
101 | - Functions are serialized with `func.toString()`, no closure properties are serialized
|
102 | - Multiple references to the same object become copies
|
103 | - Circular references are encoded as `{$circularReference:true}`
|
104 |
|
105 | ## License
|
106 |
|
107 | toSource is open source software under the [zlib license][2].
|
108 |
|
109 | [1]: https://github.com/marcello3d/node-tosource/blob/master/src/tosource.test.ts
|
110 | [2]: https://github.com/marcello3d/node-tosource/blob/master/LICENSE
|