Node.js worker threads shared object/store
ECMA Script contains no shared objects but it have SharedArrayBuffer
. And you can implement such behavior on your own writing data directly in buffer using DataView
and wrapper:
// Shared valueclass SharedPoint { constructor(array) { this.dataview = new DataView(array); } set x(value) { this.dataview.setUint8(0, value); } set y(value) { this.dataview.setUint8(1, value); } get x() { return this.dataview.getUint8(0); } get y() { return this.dataview.getUint8(1); }}// Usageconst buffer = new SharedArrayBuffer(2);// Create two instances of shared point.const point0 = new SharedPoint(buffer);const point1 = new SharedPoint(buffer);// Get initial values for point #1console.log('x', point1.x); // 0console.log('y', point1.y); // 0// Update point #0point0.x = 64;point0.y = 32;// Get changes in point #1console.log('x', point1.x); // 64console.log('y', point1.y); // 32
You are able to create class which can manipulate strings or C-like structures. While SharedArrayBuffer
is tranferable object it can be shared between worker and main process.
⚠️ Note Due to Spectre attack
SharedArrayBuffer
was disabled by all major browsers and reenabled in Chrome since version 68 and in Firefox since version 79. Check browsers support on can i use.