child_process.fork() allows one module to spawn a new node environment with specified environment variables. The two processes can send messages to each other via send(), and receive those messages via 'message' events.
For example, if your current main module is named server.js, then you could add a temporary start.js module (which will be the new lambda function) in the same directory that looks something like this:
// Add NODE_DEBUG to this process's 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 modified slightly 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
});
});
});
// The rest of your original code ...
exports.myHandler = function (event, context, callback) {
// Whatever you need here...
}