333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
stringifier
================================
 
Yet another stringify function.
 
[![Build Status][travis-image]][travis-url]
[![NPM package][npm-image]][npm-url]
[![Bower package][bower-image]][bower-url]
[![License][license-image]][license-url]
 
 
DESCRIPTION
---------------------------------------
 
`stringifier` is a function like `JSON.stringify` but intended to be more customizable. For example,
 
- Max depth for recursive object tree traversal
- Per-type output customization
- Circular reference handling
 
 
Pull-requests, issue reports and patches are always welcomed. `stringifier` is a spin-off product of [power-assert](https://github.com/power-assert-js/power-assert) project.
 
 
API
---------------------------------------
 
 
### stringifier(options)
 
`require('stringifier')` exports single function `stringifier` that accepts `options` as optional parameters and returns configured function for stringify. This is the comprehensive usage.
 
```javascript
var stringifier = require('stringifier');
var stringify = stringifier(options);
console.log(stringify(anyVar));
```
 
 
### stringifier.stringify(val, options)
 
For more simplified usage, `stringifier` has a function `stringify`, that simply takes target object/value and returns stringified result string. `stringifier.stringify` accepts `options` as optional parameter too.
 
```javascript
var stringify = require('stringifier').stringify;
console.log(stringify(anyVar));
```
 
 
INSTALL
---------------------------------------
 
### via npm
 
Install
 
    $ npm install --save stringifier
 
Use
 
```javascript
var stringify = require('stringifier').stringify;
console.log(stringify(anyVar));
```
 
#### use stringifier npm module on browser
 
`stringifier` function is exported
 
    <script type="text/javascript" src="./path/to/node_modules/stringifier/build/stringifier.js"></script>
 
 
### via bower
 
Install
 
    $ bower install --save stringifier
 
Load (`stringifier` function is exported)
 
    <script type="text/javascript" src="./path/to/bower_components/stringifier/build/stringifier.js"></script>
 
Use
 
```javascript
console.log(stringifier.stringify(anyVar));
```
 
 
EXAMPLE
---------------------------------------
 
For given context,
 
```javascript
var stringifier = require('stringifier'),
    assert = require('assert');
 
function Student (name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
}
 
var AnonStudent = function(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
};
 
var student = new Student('tom', 10, 'M');
var anonStudent = new AnonStudent('mary', 9, 'F');
 
var values = [
    'string', 
    [null, undefined],
    {
        primitives: [true, false, -5, 98.6],
        specific: {
            regex: /^not/,
            numbers: [NaN, Infinity, -Infinity]
        },
        userDefined: [
            student,
            anonStudent
        ]
    }
];
```
 
 
#### default single-line output
 
```javascript
var stringify = stringifier();
console.log(stringify(values));
```
result:
 
```javascript
["string",[null,undefined],Object{primitives:[true,false,-5,98.6],specific:Object{regex:/^not/,numbers:[NaN,Infinity,-Infinity]},userDefined:[Student{name:"tom",age:10,gender:"M"},@Anonymous{name:"mary",age:9,gender:"F"}]}]
```
 
 
#### pretty printing with indentation
 
Use `indent` option for pretty printing. Using four spaces for indentation in this case.
 
```javascript
var stringify = stringifier({indent: '    '});
console.log(stringify(values));
```
 
result:
 
```javascript
[
    "string",
    [
        null,
        undefined
    ],
    Object{
        primitives: [
            true,
            false,
            -5,
            98.6
        ],
        specific: Object{
            regex: /^not/,
            numbers: [
                NaN,
                Infinity,
                -Infinity
            ]
        },
        userDefined: [
            Student{
                name: "tom",
                age: 10,
                gender: "M"
            },
            @Anonymous{
                name: "mary",
                age: 9,
                gender: "F"
            }
        ]
    }
]
```
 
 
#### depth limitation
 
Use `maxDepth` option to stringify at most specified levels.
 
```javascript
var stringify = stringifier({maxDepth: 3, indent: '    '});
console.log(stringify(values));
```
 
result:
 
```javascript
[
    "string",
    [
        null,
        undefined
    ],
    Object{
        primitives: [
            true,
            false,
            -5,
            98.6
        ],
        specific: Object{
            regex: /^not/,
            numbers: #Array#
        },
        userDefined: [
            #Student#,
            #@Anonymous#
        ]
    }
]
```
 
 
#### anonymous class label
 
Use `anonymous` option to specify alternate type name for anonymous constructors.
 
```javascript
var stringify = stringifier({anonymous: 'ANON'});
assert(stringify(anonStudent) === 'ANON{name:"mary",age:9,gender:"F"}');
```
 
 
#### omit specific property from output
 
Customize `options.handlers`
 
```javascript
var stringify;
 
// property whitelist and reordering
stringify = stringifier({
    handlers: {
        'Student': s.object(null, ['gender', 'age'])
    }
});
assert(stringify(student) === 'Student{gender:"M",age:10}');
 
// blacklist by property name
stringify = stringifier({
    handlers: {
        'Student': s.object(function (kvp) {
            return ['age', 'gender'].indexOf(kvp.key) === -1;
        })
    }
});
assert(stringify(student) === 'Student{name:"tom"}');
 
// blacklist by property value
stringify = stringifier({
    handlers: {
        'Student': s.object(function (kvp) {
            return kvp.value !== 'M';
        })
    }
});
assert(stringify(student) === 'Student{name:"tom",age:10}');
 
// whitelist by property value
stringify = stringifier({
    handlers: {
        'Student': s.object(function (kvp) {
            return typeName(kvp.value) === 'string';
        })
    }
});
assert(stringify(student) === 'Student{name:"tom",gender:"M"}');
```
 
 
#### truncate property value
 
Return number from object predicate
 
```javascript
stringify = stringifier({
    handlers: {
        'Student': s.object(function (kvp) {
            if (kvp.key === 'name') {
                return 3;
            }
            return true;
        })
    }
});
assert(stringify(student) === 'Student{name:"to..(snip),age:10,gender:"M"}');
```
 
 
 
CONFIGURATION
---------------------------------------
 
### options
 
 
#### options.maxDepth
Type: `number`
Default value: `null`
 
Max depth for recursive Object tree traversal
 
 
#### options.indent
Type: `String`
Default value: `null`
 
string value for indentation.
If this value is not empty, stringified result may contain multiple lines.
 
 
#### options.lineSeparator
Type: `String`
Default value: `'\n'`
 
string value for line-separator.
Makes sense only if `options.indent` is not empty.
 
 
#### options.anonymous
Type: `String`
Default value: `'@Anonymous'`
 
Type name string alternative for displaying Object created by anonymous constructor
 
 
#### options.circular
Type: `String`
Default value: `'#@Circular#'`
 
Alternative string for displaying Circular reference
 
 
#### options.snip
Type: `String`
Default value: `'..(snip)'`
 
For displaying truncated string
 
 
#### options.handlers
 
`options.handlers` is a object where property names are type names (string, number, ...) and values are per-type stringify strategy functions. Various strategies are defined in `stringifier.strategies`, and default strategies are defined as follows.
 
```javascript
var s = require('./strategies');
function defaultHandlers () {
    return {
        'null': s.always('null'),
        'undefined': s.always('undefined'),
        'function': s.prune(),
        'string': s.json(),
        'boolean': s.json(),
        'number': s.number(),
        'symbol': s.toStr(),
        'RegExp': s.toStr(),
        'String': s.newLike(),
        'Boolean': s.newLike(),
        'Number': s.newLike(),
        'Date': s.newLike(),
        'Array': s.array(),
        'Object': s.object(),
        'Error': s.object(null, ['message', 'code']),
        '@default': s.object()
    };
}
```
 
If unknown type is detected, strategy function registered by `'@default'` key will be used.
 
 
### strategies
 
For given `Student` pseudo-class and a `stringifier`,
 
```javascript
var stringifier = require('stringifier'),
    s = stringifier.strategies,
    assert = require('assert'),
 
function Student (name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
}
 
var student = new Student('tom', 10, 'M');
```
 
#### always
 
`always` strategy always returns passed constant (In this case, `'foo'`).
 
```javascript
var stringify = stringifier({
    handlers: {
        'Student': s.always('foo')
    }
});
assert(stringify(student) === 'foo');
```
 
#### json
 
`json` strategy applies `JSON.stringify` to input value then return the result string.
 
```javascript
var stringify = stringifier({
    handlers: {
        'Student': s.json()
    }
});
assert(stringify(student) === '{"name":"tom","age":10,"gender":"M"}');
```
 
#### toStr
 
`toStr` strategy calls `toString()` to input value then return the result string.
 
```javascript
var stringify = stringifier({
    handlers: {
        'Student': s.toStr()
    }
});
assert(stringify(student) === '[object Object]');
```
 
#### prune
 
`prune` strategy does not serialize target value but returns target type name surrounded by `#`.
 
```javascript
var stringify = stringifier({
    handlers: {
        'Student': s.prune()
    }
});
assert(stringify(student) === '#Student#');
```
 
#### newLike
 
`newLike` strategy emulates "new constructor call pattern".
 
```javascript
var stringify = stringifier({
    handlers: {
        'Student': s.newLike()
    }
});
assert(stringify(student) === 'new Student({"name":"tom","age":10,"gender":"M"})');
```
 
#### object
 
`object` strategy stringifies target object recursively and decorate object literal-like syntax with its type name. `object` is a default strategy for objects, and any other unknown types.
 
```javascript
var stringify = stringifier({
    handlers: {
        'Student': s.object()
    }
});
assert(stringify(student) === 'Student{name:"tom",age:10,gender:"M"}');
```
 
#### array
 
`array` strategy is an array specific stringification strategy, and is a default strategy for arrays.
 
```javascript
var stringify = stringifier({
    handlers: {
        'Array': s.array()
    }
});
assert(stringify(['foo', 'bar', 'baz']) === '["foo","bar","baz"]');
```
 
#### number
 
`number` strategy is a number specific stringification strategy, and is a default strategy for number. `number` strategy also provides `NaN`,`Infinity` and `-Infinity` handling.
 
```javascript
var stringify = stringifier({
    handlers: {
        'Array': s.array(),
        'number': s.number()
    }
});
assert(stringify([NaN, 0, Infinity, -0, -Infinity]) === '[NaN,0,Infinity,0,-Infinity]');
```
 
 
AUTHOR
---------------------------------------
* [Takuto Wada](https://github.com/twada)
 
 
LICENSE
---------------------------------------
Licensed under the [MIT](https://twada.mit-license.org/2014-2018) license.
 
 
[travis-url]: https://travis-ci.org/twada/stringifier
[travis-image]: https://secure.travis-ci.org/twada/stringifier.svg?branch=master
 
[npm-url]: https://npmjs.org/package/stringifier
[npm-image]: https://badge.fury.io/js/stringifier.svg
 
[bower-url]: https://badge.fury.io/bo/stringifier
[bower-image]: https://badge.fury.io/bo/stringifier.svg
 
[license-url]: https://twada.mit-license.org/2014-2018
[license-image]: https://img.shields.io/badge/license-MIT-brightgreen.svg