Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best module for shared memory in node js? [closed]

Tags:

node.js

I want to share memory between two individual processes.Can anyone suggest me what will be the best module used in node js.I want to save data in an large array in json format and shared between two process.I am using shm-typed-array module but due to less resources i couldn't solve the issue.

Here is code:

Parent.js:-------------------

"use strict";

const shm = require('shm-typed-array');
const fork = require('child_process').fork;

// Create shared memory
const SIZE = 20000000;
const data = shm.create(SIZE, 'Float64Array');

// Fill with dummy data
Array.prototype.fill.call(data, 1);

// Spawn child, set up communication, and give shared memory
const child = fork("child.js");
child.on('message', sum => {
    console.log(`Got answer: ${sum}`);

    // Demo only; ideally you'd re-use the same child
    child.kill();
});
child.send(data.key);

Child.js:---------------

"use strict";

const shm = require('shm-typed-array');

process.on('message', key => {
    // Get access to shared memory
    const data = shm.get(key, 'Float64Array');

    // Perform processing
    const sum = Array.prototype.reduce.call(data, (a, b) => a + b, 0);

    // Return processed data
    process.send(sum);
});

Please any suggestion....

like image 289
Probir Avatar asked Jun 30 '17 09:06

Probir


People also ask

Is multithreading possible in node JS?

Node. js runs JavaScript code in a single thread, which means that your code can only do one task at a time. However, Node. js itself is multithreaded and provides hidden threads through the libuv library, which handles I/O operations like reading files from a disk or network requests.


1 Answers

I would recommend going with Redis currently. This is just a little thrown together example of incrementing a counter every second with redis. You can use .get across processes. If you're looking for a windows version of redis, you can get it here https://github.com/dmajkic/redis/downloads

const redis = require('redis');
const client = redis.createClient();

setInterval(() => {
    client.get("count", (error, data) => {
        data = JSON.parse(data);
        data++;
        client.set("count", data);
    });
}, 1000);
like image 93
Jeff Avatar answered Oct 03 '22 03:10

Jeff