child_process.fork () allows a single module to create a new node environment with the specified environment variables. These two processes can send messages to each other via send() and receive these messages through message events.
For example, if your current main module is named server.js , you can add a temporary start.js module (which will be a new lambda function) in the same directory, which looks something like this:
// Add NODE_DEBUG to this process environment variables, which are passed by default to // the forked node environment. process.env.NODE_DEBUG = 'https'; const cp = require('child_process'); const n = cp.fork('server.js'); // Cached callback functions, in case client can pass in different callbacks. // Use an object instead of array, to avoid memory leaks. const cbs = {}; var cbIndexCounter = 0; // To make callback indices unique // Call appropriate callback with response from child process, and delete cached callback. n.on('message', (m) => { cbs[m.cbIndex](m.error, m.result); delete cbs[m.cbIndex]; }); n.on('error', (err) => { console.log('Child node env error: ', err); }); // Cache the callback; forward event, context, index to child process; and increment index. exports.myHandler = function(event, context, callback) { cbs[cbIndexCounter] = callback; n.send({ event: event, context: context, cbIndex: cbIndexCounter++ }); }
The server.js module can be slightly modified by adding a message event listener:
process.on('message', (m) => { exports.myHandler(m.event, m.context, function(error, result) { process.send({ error: error, result: result, cbIndex: m.cbIndex }); }); });
cybersam
source share