shmmap 🐏
Native bindings for mmap complemented with POSIX shm for creating (and safely destroying) actual shared memory segments for sharing large data between node.js processes beneath things like Buffer / Uint8Array.
$ npm install --save shmmap
Example
In parent.js:
const cp = ;const shmmap = ; // create a 4 MiB bufferlet nl_test = 4 * 1024 * 1024;let s_key at_test = shmmap; // write some data to itlet nl_half = nl_test>>1;forlet i_write=0; i_write<nl_half; i_write++ at_testi_write = i_write % 255;; // spawn another processlet u_proc = cp; // wait for process to exitu_proc;
In child.js:
const shmmap = ; // open shared memory segmentlet at_shared = shmmap; // count sumlet c_sum = 0;let nl_half = +processargv4;forlet i_read=0; i_read<nl_half; i_read++ c_sum += at_sharedi_read; // write a value to zero-th positionat_shared0 = 100; // output sum to consoleconsole;
Results
child sum: 2097152
parent sum: 2097251
parent 0: 100
As we can see, the 'child' successfully mutates the zero-th value in the buffer that is shared between the two processes.
API
shmmap.create(byteLength: uint)
-- creates a Buffer with the given byteLength
atop a new shared memory segment.
- returns an Array of
[key: path, data: buffer]
-- wherekey
is the string you would pass over IPC to another process to open the shared memory segment somewhere else.
shmmap.read(key: path, byteLength: uint)
-- creates a Buffer with the given byteLength
atop an existing shared memory segment, in read-only mode.
- returns the Buffer
shmmap.read_write(key: path, byteLength: uint)
-- creates a Buffer with the given byteLength
atop an existing shared memory segment, in read-write mode.
- returns the Buffer
shmmap.release(key: path)
-- releases the current process' hold on the shared memory segment at key
.
- returns
undefined