{"id":13526286,"url":"https://github.com/mongodb/js-bson","last_synced_at":"2025-05-16T01:03:29.972Z","repository":{"id":2667038,"uuid":"3658431","full_name":"mongodb/js-bson","owner":"mongodb","description":"BSON Parser for node and browser","archived":false,"fork":false,"pushed_at":"2025-05-05T17:31:00.000Z","size":11620,"stargazers_count":1179,"open_issues_count":10,"forks_count":257,"subscribers_count":52,"default_branch":"main","last_synced_at":"2025-05-09T00:55:46.795Z","etag":null,"topics":["bson","bson-library","mongodb","node-js","nodejs"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mongodb.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2012-03-08T09:15:24.000Z","updated_at":"2025-05-06T18:13:38.000Z","dependencies_parsed_at":"2023-01-14T11:04:28.280Z","dependency_job_id":"ffebae1b-b8d3-435c-a6ce-ad901b27a741","html_url":"https://github.com/mongodb/js-bson","commit_stats":{"total_commits":830,"total_committers":112,"mean_commits":7.410714285714286,"dds":0.653012048192771,"last_synced_commit":"eba09e7a432ad36f8bfd232013135efa5e576445"},"previous_names":[],"tags_count":151,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fjs-bson","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fjs-bson/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fjs-bson/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fjs-bson/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mongodb","download_url":"https://codeload.github.com/mongodb/js-bson/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253421525,"owners_count":21905769,"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":["bson","bson-library","mongodb","node-js","nodejs"],"created_at":"2024-08-01T06:01:27.524Z","updated_at":"2025-05-16T01:03:24.920Z","avatar_url":"https://github.com/mongodb.png","language":"TypeScript","readme":"# BSON parser\n\nBSON is short for \"Binary JSON,\" and is the binary-encoded serialization of JSON-like documents.\nYou can learn more about it in [the specification](http://bsonspec.org).\n\n### Table of Contents\n\n- [Usage](#usage)\n- [Bugs/Feature Requests](#bugs--feature-requests)\n- [Installation](#installation)\n- [Documentation](#documentation)\n- [FAQ](#faq)\n\n\n### Release Integrity\n\nReleases are created automatically and signed using the [Node team's GPG key](https://pgp.mongodb.com/node-driver.asc). This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:\n\n```shell\ngpg --import node-driver.asc\n```\n\nThe GitHub release contains a detached signature file for the NPM package (named\n`bson-X.Y.Z.tgz.sig`).\n\nThe following command returns the link npm package. \n```shell\nnpm view bson@vX.Y.Z dist.tarball \n```\n\nUsing the result of the above command, a `curl` command can return the official npm package for the release.\n\nTo verify the integrity of the downloaded package, run the following command:\n```shell\ngpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz\n```\n\n\u003e[!Note]\nNo verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.\n\n## Bugs / Feature Requests\n\nThink you've found a bug? Want to see a new feature in `bson`? Please open a case in our issue management tool, JIRA:\n\n1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org)\n2. Navigate to the NODE project: [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE)\n3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it.\n\nBug reports in JIRA for the NODE driver project are **public**.\n\n## Usage\n\nTo build a new version perform the following operations:\n\n```\nnpm install\nnpm run build\n```\n\n### Node.js or Bundling Usage\n\nWhen using a bundler or Node.js you can import bson using the package name:\n\n```js\nimport { BSON, EJSON, ObjectId } from 'bson';\n// or:\n// const { BSON, EJSON, ObjectId } = require('bson');\n\nconst bytes = BSON.serialize({ _id: new ObjectId() });\nconsole.log(bytes);\nconst doc = BSON.deserialize(bytes);\nconsole.log(EJSON.stringify(doc));\n// {\"_id\":{\"$oid\":\"...\"}}\n```\n\n### Browser Usage\n\nIf you are working directly in the browser without a bundler please use the `.mjs` bundle like so:\n\n```html\n\u003cscript type=\"module\"\u003e\n  import { BSON, EJSON, ObjectId } from './lib/bson.mjs';\n\n  const bytes = BSON.serialize({ _id: new ObjectId() });\n  console.log(bytes);\n  const doc = BSON.deserialize(bytes);\n  console.log(EJSON.stringify(doc));\n  // {\"_id\":{\"$oid\":\"...\"}}\n\u003c/script\u003e\n```\n\n## Installation\n\n```sh\nnpm install bson\n```\n\n### MongoDB Node.js Driver Version Compatibility\n\nOnly the following version combinations with the [MongoDB Node.js Driver](https://github.com/mongodb/node-mongodb-native) are considered stable.\n\n|               | `bson@1.x` | `bson@4.x` | `bson@5.x` | `bson@6.x` |\n| ------------- | ---------- | ---------- | ---------- | ---------- |\n| `mongodb@6.x` | N/A        | N/A        | N/A        | ✓          |\n| `mongodb@5.x` | N/A        | N/A        | ✓          | N/A        |\n| `mongodb@4.x` | N/A        | ✓          | N/A        | N/A        |\n| `mongodb@3.x` | ✓          | N/A        | N/A        | N/A        |\n\n## Documentation\n\n### BSON\n\n[API documentation](https://mongodb.github.io/node-mongodb-native/Next/modules/BSON.html)\n\n\u003ca name=\"EJSON\"\u003e\u003c/a\u003e\n\n### EJSON\n\n- [EJSON](#EJSON)\n\n  - [.parse(text, [options])](#EJSON.parse)\n\n  - [.stringify(value, [replacer], [space], [options])](#EJSON.stringify)\n\n  - [.serialize(bson, [options])](#EJSON.serialize)\n\n  - [.deserialize(ejson, [options])](#EJSON.deserialize)\n\n\u003ca name=\"EJSON.parse\"\u003e\u003c/a\u003e\n\n#### _EJSON_.parse(text, [options])\n\n| Param             | Type                 | Default           | Description                                                                        |\n| ----------------- | -------------------- | ----------------- | ---------------------------------------------------------------------------------- |\n| text              | \u003ccode\u003estring\u003c/code\u003e  |                   |                                                                                    |\n| [options]         | \u003ccode\u003eobject\u003c/code\u003e  |                   | Optional settings                                                                  |\n| [options.relaxed] | \u003ccode\u003eboolean\u003c/code\u003e | \u003ccode\u003etrue\u003c/code\u003e | Attempt to return native JS types where possible, rather than BSON types (if true) |\n\nParse an Extended JSON string, constructing the JavaScript value or object described by that\nstring.\n\n**Example**\n\n```js\nconst { EJSON } = require('bson');\nconst text = '{ \"int32\": { \"$numberInt\": \"10\" } }';\n\n// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }\nconsole.log(EJSON.parse(text, { relaxed: false }));\n\n// prints { int32: 10 }\nconsole.log(EJSON.parse(text));\n```\n\n\u003ca name=\"EJSON.stringify\"\u003e\u003c/a\u003e\n\n#### _EJSON_.stringify(value, [replacer], [space], [options])\n\n| Param             | Type                                        | Default           | Description                                                                                                                                                                                                                                                                                                                                        |\n| ----------------- | ------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| value             | \u003ccode\u003eobject\u003c/code\u003e                         |                   | The value to convert to extended JSON                                                                                                                                                                                                                                                                                                              |\n| [replacer]        | \u003ccode\u003efunction\u003c/code\u003e \\| \u003ccode\u003earray\u003c/code\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| [space]           | \u003ccode\u003estring\u003c/code\u003e \\| \u003ccode\u003enumber\u003c/code\u003e  |                   | A String or Number object that's used to insert white space into the output JSON string for readability purposes.                                                                                                                                                                                                                                  |\n| [options]         | \u003ccode\u003eobject\u003c/code\u003e                         |                   | Optional settings                                                                                                                                                                                                                                                                                                                                  |\n| [options.relaxed] | \u003ccode\u003eboolean\u003c/code\u003e                        | \u003ccode\u003etrue\u003c/code\u003e | Enabled Extended JSON's `relaxed` mode                                                                                                                                                                                                                                                                                                             |\n| [options.legacy]  | \u003ccode\u003eboolean\u003c/code\u003e                        | \u003ccode\u003etrue\u003c/code\u003e | Output in Extended JSON v1                                                                                                                                                                                                                                                                                                                         |\n\nConverts a BSON document to an Extended JSON string, optionally replacing values if a replacer\nfunction is specified or optionally including only the specified properties if a replacer array\nis specified.\n\n**Example**\n\n```js\nconst { EJSON } = require('bson');\nconst Int32 = require('mongodb').Int32;\nconst doc = { int32: new Int32(10) };\n\n// prints '{\"int32\":{\"$numberInt\":\"10\"}}'\nconsole.log(EJSON.stringify(doc, { relaxed: false }));\n\n// prints '{\"int32\":10}'\nconsole.log(EJSON.stringify(doc));\n```\n\n\u003ca name=\"EJSON.serialize\"\u003e\u003c/a\u003e\n\n#### _EJSON_.serialize(bson, [options])\n\n| Param     | Type                | Description                                          |\n| --------- | ------------------- | ---------------------------------------------------- |\n| bson      | \u003ccode\u003eobject\u003c/code\u003e | The object to serialize                              |\n| [options] | \u003ccode\u003eobject\u003c/code\u003e | Optional settings passed to the `stringify` function |\n\nSerializes an object to an Extended JSON string, and reparse it as a JavaScript object.\n\n\u003ca name=\"EJSON.deserialize\"\u003e\u003c/a\u003e\n\n#### _EJSON_.deserialize(ejson, [options])\n\n| Param     | Type                | Description                                  |\n| --------- | ------------------- | -------------------------------------------- |\n| ejson     | \u003ccode\u003eobject\u003c/code\u003e | The Extended JSON object to deserialize      |\n| [options] | \u003ccode\u003eobject\u003c/code\u003e | Optional settings passed to the parse method |\n\nDeserializes an Extended JSON object into a plain JavaScript object with native/BSON types\n\n## Error Handling\n\nIt is our recommendation to use `BSONError.isBSONError()` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. We guarantee `BSONError.isBSONError()` checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.\n\nAny new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release.\nThis means `BSONError.isBSONError()` will always be able to accurately capture the errors that our BSON library throws.\n\nHypothetical example: A collection in our Db has an issue with UTF-8 data:\n\n```ts\nlet documentCount = 0;\nconst cursor = collection.find({}, { utf8Validation: true });\ntry {\n  for await (const doc of cursor) documentCount += 1;\n} catch (error) {\n  if (BSONError.isBSONError(error)) {\n    console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`);\n    return documentCount;\n  }\n  throw error;\n}\n```\n\n## React Native\n\nBSON vendors the required polyfills for `TextEncoder`, `TextDecoder`, `atob`, `btoa` imported from React Native and therefore doesn't expect users to polyfill these. One additional polyfill, `crypto.getRandomValues` is recommended and can be installed with the following command:\n\n```sh\nnpm install --save react-native-get-random-values\n```\n\nThe following snippet should be placed at the top of the entrypoint (by default this is the root `index.js` file) for React Native projects using the BSON library. These lines must be placed for any code that imports `BSON`.\n\n```typescript\n// Required Polyfills For ReactNative\nimport 'react-native-get-random-values';\n```\n\nFinally, import the `BSON` library like so:\n\n```typescript\nimport { BSON, EJSON } from 'bson';\n```\n\nThis will cause React Native to import the `node_modules/bson/lib/bson.rn.cjs` bundle (see the `\"react-native\"` setting we have in the `\"exports\"` section of our [package.json](./package.json).)\n\n### Technical Note about React Native module import\n\nThe `\"exports\"` definition in our `package.json` will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in [React Native's runtime hermes](https://hermesengine.dev/).\n\n## FAQ\n\n#### Why does `undefined` get converted to `null`?\n\nThe `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys.\n\n#### How do I add custom serialization logic?\n\nThis library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize.\n\n```javascript\nconst BSON = require('bson');\n\nclass CustomSerialize {\n  toBSON() {\n    return 42;\n  }\n}\n\nconst obj = { answer: new CustomSerialize() };\n// \"{ answer: 42 }\"\nconsole.log(BSON.deserialize(BSON.serialize(obj)));\n```\n","funding_links":[],"categories":["Repository","file format (文件格式)","Uncategorized","TypeScript"],"sub_categories":["Object / JSON / JSON Schema","Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongodb%2Fjs-bson","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmongodb%2Fjs-bson","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongodb%2Fjs-bson/lists"}