Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging two or more node.js require modules into one namespace

Tags:

node.js

Google Flatbuffers creates in (AMD?) module for each table that one wants. I have them all in one name space called PNTCI.

Right now, I am doing something ugly and non-intuitve to merge the name spaces together by doing successive includes to the PNTCI namespace like this:

const telem = require('../messages/Telemetry_generated').PNTCI
const PNTCI = Object.assign(telem, require('../messages/header_generated').PNTCI)

The again the reason is that the autogenerated require modules have a old fashioned format that looks like this for the Header_generated.js :

// automatically generated by the FlatBuffers compiler, do not modify

/**
 * @const
 * @namespace
 */
var PNTCI = PNTCI || {};

/**
 * Common header for all PNTCI message payloads
 *
 * @constructor
 */

and the end of the file looks like this:

/**
 * @param {flatbuffers.Builder} builder
 * @param {flatbuffers.Offset} offset
 */
PNTCI.Header.finishHeaderBuffer = function(builder, offset) {
  builder.finish(offset);
};

// Exports for Node.js and RequireJS
this.PNTCI = PNTCI;

and for Telemetry_generated.js

// automatically generated by the FlatBuffers compiler, do not modify

/**
 * @const
 * @namespace
 */
var PNTCI = PNTCI || {};

/**
 * @constructor
 */
PNTCI.PosVector = function() {
  /**
   * @type {flatbuffers.ByteBuffer}
   */
  this.bb = null;

and then the end of the file looks like this:

PNTCI.Telemetry.finishTelemetryBuffer = function(builder, offset) {
  builder.finish(offset);
};

// Exports for Node.js and RequireJS
this.PNTCI = PNTCI;
like image 799
Dr.YSG Avatar asked Sep 18 '26 06:09

Dr.YSG


1 Answers

The use of namespaces isn't idiomatic to Node.js because a module itself acts as a namespace, so the problem is specific to these particular modules.

It can be written shorter with object spread syntax:

const PNTCI = {
  ...require('../messages/Telemetry_generated').PNTCI,
  ...require('../messages/header_generated').PNTCI
};

Which is syntactic sugar for:

const PNTCI = Object.assign({},
  require('../messages/Telemetry_generated').PNTCI,
  require('../messages/header_generated').PNTCI
);

If these modules are constantly used together, it may be beneficial to re-export them as single module:

module.exports = {
  ...require('../messages/Telemetry_generated').PNTCI,
  ...require('../messages/header_generated').PNTCI
};

Since there's generally no need for namespaces in Node, merging modules under single PNTCI variable may be unneeded; modules could be imported separately to different variables. This makes the application more modular if only some of these modules are used in some places.

like image 51
Estus Flask Avatar answered Sep 20 '26 14:09

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!