No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

json-module.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. "use strict";
  2. module.exports = json_module;
  3. var util = require("../util");
  4. var protobuf = require("../..");
  5. json_module.description = "JSON representation as a module";
  6. function jsonSafeProp(json) {
  7. return json.replace(/^( +)"(\w+)":/mg, function($0, $1, $2) {
  8. return protobuf.util.safeProp($2).charAt(0) === "."
  9. ? $1 + $2 + ":"
  10. : $0;
  11. });
  12. }
  13. function json_module(root, options, callback) {
  14. try {
  15. var rootProp = protobuf.util.safeProp(options.root || "default");
  16. var output = [
  17. (options.es6 ? "const" : "var") + " $root = ($protobuf.roots" + rootProp + " || ($protobuf.roots" + rootProp + " = new $protobuf.Root()))\n"
  18. ];
  19. if (root.options) {
  20. var optionsJson = jsonSafeProp(JSON.stringify(root.options, null, 2));
  21. output.push(".setOptions(" + optionsJson + ")\n");
  22. }
  23. var json = jsonSafeProp(JSON.stringify(root.nested, null, 2).trim());
  24. output.push(".addJSON(" + json + ");");
  25. output = util.wrap(output.join(""), protobuf.util.merge({ dependency: "protobufjs/light" }, options));
  26. process.nextTick(function() {
  27. callback(null, output);
  28. });
  29. } catch (e) {
  30. return callback(e);
  31. }
  32. return undefined;
  33. }