UNPKG

1.19 kBJavaScriptView Raw
1///@ts-check
2'use strict';
3
4var through2 = require('through2');
5var json5 = require('json5');
6
7/**
8 *
9 * @param {string} json
10 * @param {boolean} pretty
11 */
12function mini(json, pretty) {
13 var data = json5.parse(json);
14 return JSON.stringify(data, undefined, pretty ? 4 : 0);
15}
16
17/**
18 *
19 * @param {boolean} [pretty] - 格式化输出
20 */
21function jsonMinify(pretty) {
22 return through2.obj((file, enc, cb) => {
23 var err = null;
24 if (file.isNull()) {
25 return cb(null, file);
26 }
27 if (file.isBuffer()) {
28 try {
29 file.contents = Buffer.from(mini(file.contents.toString(), pretty));
30 } catch (error) {
31 err = error
32 err.fileName = file.path;
33 }
34 }
35 if (file.isStream()) {
36 file.contents = file.contents.pipe(through2.obj((json, enc, cb) => {
37 try {
38 cb(null, mini(json.toString(), pretty));
39 } catch (error) {
40 error.fileName = file.path;
41 cb(error);
42 }
43 }));
44 }
45 cb(err, file);
46 });
47}
48module.exports = jsonMinify;
\No newline at end of file