{"id":15834473,"url":"https://github.com/kaelzhang/node-code-stringify","last_synced_at":"2025-03-15T08:31:54.365Z","repository":{"id":9765238,"uuid":"11733882","full_name":"kaelzhang/node-code-stringify","owner":"kaelzhang","description":"The node.js module that converts JavaScript variables into source codes. Unlike `JSON.stringify`, code-stringify also deals with reference(object) types of variables.","archived":false,"fork":false,"pushed_at":"2019-04-26T08:44:35.000Z","size":41,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-10T23:16:41.951Z","etag":null,"topics":["code","javascript","nodejs","serialization","stringify"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kaelzhang.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-07-29T07:39:14.000Z","updated_at":"2021-11-27T12:04:25.000Z","dependencies_parsed_at":"2022-09-26T20:41:23.101Z","dependency_job_id":null,"html_url":"https://github.com/kaelzhang/node-code-stringify","commit_stats":null,"previous_names":["kaelzhang/node-code-this"],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kaelzhang%2Fnode-code-stringify","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kaelzhang%2Fnode-code-stringify/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kaelzhang%2Fnode-code-stringify/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kaelzhang%2Fnode-code-stringify/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kaelzhang","download_url":"https://codeload.github.com/kaelzhang/node-code-stringify/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243707282,"owners_count":20334613,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["code","javascript","nodejs","serialization","stringify"],"created_at":"2024-10-05T14:01:32.760Z","updated_at":"2025-03-15T08:31:54.022Z","avatar_url":"https://github.com/kaelzhang.png","language":"JavaScript","readme":"[![Build Status](https://travis-ci.org/kaelzhang/node-code-stringify.svg?branch=master)](https://travis-ci.org/kaelzhang/node-code-stringify)\n[![Coverage](https://codecov.io/gh/kaelzhang/node-code-stringify/branch/master/graph/badge.svg)](https://codecov.io/gh/kaelzhang/node-code-stringify)\n\n# code-stringify\n\n`code-stringify` is the node.js module that converts JavaScript variables into source codes with indents and styles.\n\nUnlike `JSON.stringify`, `code-stringify` also deals with reference(object) types of variables, and it converts JavaScript variables into strings of codes, not JSON.\n\nSupports:\n\n- **Primative variables**\n- **Regular expressions**\n- **Functions**\n- **Arrays**\n- **Your custom formatter**\n\n## Installation\n\n```sh\nnpm i code-stringify\n```\n\n## Usage\n\n```js\nconst fs = require('fs')\nconst stringify = require('code-stringify')\n\nconst obj = {\n  '0': 1,\n  'a': function(n){return n;},\n  'b': 1,\n  'c-d': 3\n}\n\n// So you can use code-stringify to save your javascript variables into a file:\nfs.writeFileSync(\n  'output.js',\n  `module.exports = ${stringify(obj, null, 2)}`\n)\n```\n\nThen 'output.js' will look like:\n\n```js\nmodule.exports = {\n  0: 1,\n  a: function(n){return n;},\n  b: 1,\n  'c-d': 3\n}\n```\n\n## stringify(subject, replacer, space, indent): string\n\n##### subject `any`\n\nThe subject to be stringified\n\n##### replacer `Function(key, value) | Array`\n\nThe `replacer` argument acts just like the second parameter of `JSON.stringify`.\n\n\u003e A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.\n\n```js\nstringify({\n  a: 1,\n  b: 2\n}, function (key, value) {\n  return key === 'b'\n    ? undefined\n    : value\n})\n\n// '{a:1}'\n```\n\n##### space `number | string`\n\nThe `space` argument acts just like the third parameter of `JSON.stringify`.\n\n##### indent `number | string`\n\nDefaults to `0`\n\nThe code indent for the entire subject. If `indent === 4`, then the content of the `output.js` in the first example will be:\n\n```js\n    module.exports = {\n      0: 1,\n      a: function (n){return n;},\n      b: 1,\n      'c-d': 3\n    }\n```\n\n### new stringify.Code(string)\n\nWe could use `new code.Code(code_string)` to define an already-stringified property.\n\nSo, see the example below:\n\n```js\nconst output = `module.exports = ${stringify({\n  a: 1,\n  'foo-bar': 2,\n  foo: new stringify.Code('(function(a){return a})(3)')\n})}`\n\nsaveFile(output, 'output.js')\n```\n\nAnd the output.js will be:\n\n```\nmodule.exports = {\n  a: 1,\n  'foo-bar': 2,\n  foo: (function(a){return a})(3)\n}\n```\n\n### `stringify.STRINGIFY_SYMBOL`\n\n```js\n// `stringify.STRINGIFY_SYMBOL` equals to\nstringify.STRINGIFY_SYMBOL = Symbol.for('code.stringify.custom')\n```\n\nIf an `object[stringify.STRINGIFY_SYMBOL]` is a function, then the function will be used as the stringifier of the object.\n\n```js\nconst monkey = {\n  iam: {\n    [Symbol.for('code.stringify.custom')] () {\n      return '\"monkey king\"'\n    }\n  }\n}\n\nconsole.log(stringify(monkey))\n// {iam:\"monkey king\"}\n```\n\n### Versus `JSON.stringify()`\n\n- `JSON.stringify` makes JSON.\n- `code-stringify` makes JavaScript code.\n\n****\n\n\u003e Advanced Section\n\n```js\nconst {\n  Stringifier,\n  STRINGIFY_SYMBOL,\n  CODE_STRINGIFY_CUSTOM\n} = require('code-stringify')\n```\n\n## new Stringifier(options)\n\n\u003e new in 2.0.0\n\nThe constructor `Stringifier` allows us to take more control of the stringifer.\n\n- **options** `Object`\n  - **replacer?** `(Function | Array)=null`\n  - **space?** `(number | string)=0` Defaults to `0` which indicates there should be no spaces.\n  \u003c!-- - **detectCircular?** `boolean=false` Whether should detect circular object and throw an error if any circular reference is found --\u003e\n  - **quote?** `' | \"` the quote character for strings. Defaults to `'`.\n  - **useNumberKey?** `boolean=true` uses number key of an object if possible\n\n#### options.useNumberKey\n\n```js\nnew Stringifier().stringify({'1': 1, '2b': 2})\n// {1:1,'2b':2}\n\nnew Stringifier({\n  useNumberKey: false\n}).stringify({'1': 1, '2b': 2})\n// {'1':1:'2b':2}\n```\n\u003c!--\n#### options.detectCircular\n\nIf we try to stringify a circular object, then it will throw an `CIRCULAR_DETECTED` error instead of exceeding maximum call stack error if we set the option to `true` --\u003e\n\n### stringifier.stringify(subject, indent = 0): string\n\n- **indent?** `(number | string)=0`\n\nReturns the JavaScript code string.\n\n### stringifier.register(customStringifier): this\n\n- **customStringifier** `CustomStringifier`\n\n```ts\ninterface CustomStringifier {\n  // Test if we could use the custom stringifier\n  test: Function (subject): boolean\n  // If the test method returns true,\n  // then the stringify method will be used.\n  // Inside the method, we can access the `Stringifier` instance by `this` object, so that we can use the utility methods below\n  stringify: Function(subject, indent, options): string\n}\n```\n\nRegister a custom stringifier for certain data type.\n\n```js\nclass King {\n  constructor (name) {\n    this._name = name\n  }\n\n  selfIntroduce () {\n    return `[king ${this._name}]`\n  }\n}\n\nnew Stringifier().register({\n  test (value) {\n    return value instanceof Monkey\n  },\n  stringify (value) {\n    return this.string(value.selfIntroduce())\n  }\n})\n.stringify({\n  dinosaur: 'Godzilla',\n  ape: new King('Kong')\n})\n// {dinasaur:'Godzilla',ape:'[king Kong]'}\n```\n\n## `CODE_STRINGIFY_CUSTOM`\n\n`CODE_STRINGIFY_CUSTOM` is a built-in `CustomStringifier` to support `stringify.STRINGIFY_SYMBOL`.\n\nAnd a new `Stringifier` is not registered `CODE_STRINGIFY_CUSTOM` by default.\n\n### Utility methods\n\nThe following methods has no type checking and fault tolerance\n\nMake sure every argument that passed into the methods has been type-checked\n\n#### stringifier.string(string)\n\n- **string** `string`\n\nStringify a string\n\n#### stringifier.object(object, indent)\n\n- **object** `Object`\n\nStringify a string\n\n#### stringifier.array(array, indent)\n\n- **array** `Array`\n\nStringify an array\n\n#### stringifier.key(key)\n\n- **string** `key`\n\nStringify a property of an object.\n\n## Known Issues\n\n- `space` parameter could not affect the code indent inside functions.\n- Could not deal with variable scope so far.\n\nThose issues or tasks which should be done to enhance the module might be fixed in the future. Or there will be a million thanks if you fork and contribute ~~\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkaelzhang%2Fnode-code-stringify","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkaelzhang%2Fnode-code-stringify","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkaelzhang%2Fnode-code-stringify/lists"}